最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

algorithm - finding sequential in string using javascript - Stack Overflow

programmeradmin1浏览0评论

I am going to find sequential string of numbers in string which starts from 1. For example I have this string.

"456000123456009123456780001234000"

Here sequential strings would be

"123456", "12345678", "1234"

How can I get above result using Javascript efficiently? The code looks like this.

findSequential("456000123456009123456780001234000");
//expected output
"123456", "12345678", "1234"

***note: "1" itself is not sequential, for example:

"3938139" - has no sequence
"39381249" - has "12"

With any language's solution would be appreciated but prefer Javascript or C. Thanks for your help!

I am going to find sequential string of numbers in string which starts from 1. For example I have this string.

"456000123456009123456780001234000"

Here sequential strings would be

"123456", "12345678", "1234"

How can I get above result using Javascript efficiently? The code looks like this.

findSequential("456000123456009123456780001234000");
//expected output
"123456", "12345678", "1234"

***note: "1" itself is not sequential, for example:

"3938139" - has no sequence
"39381249" - has "12"

With any language's solution would be appreciated but prefer Javascript or C. Thanks for your help!

Share Improve this question edited Jun 19, 2020 at 0:23 Steven asked Jun 18, 2020 at 23:57 StevenSteven 6577 silver badges18 bronze badges 10
  • 1 What have you tried so far? – Flaom Commented Jun 18, 2020 at 23:58
  • 3 Generally you'll get better responses/guidance/feedback from the munity if you include what you have tried already. – Alexander Nied Commented Jun 18, 2020 at 23:59
  • 2 Why not start with 0? 0123456 – Adrian Brand Commented Jun 18, 2020 at 23:59
  • How do you define “sequential”? Should consecutive numbers always increase by +1? Should they always be integers? Why do you have a space separated string rather than an array? What have you tried so far? – Sebastian Simon Commented Jun 18, 2020 at 23:59
  • 1 Another question is: what about 1 itself? Is that a sequence? Are 1212 two sequences? Are 11 two sequences? – Sebastian Simon Commented Jun 19, 2020 at 0:17
 |  Show 5 more ments

5 Answers 5

Reset to default 2

A simple for loop should be able to achieve this. In JavaScript:

function findSequential(s) {
    const res = []
    let current = []
    let num = 1
    for(let char of s) {
      if (char == num) {
        current.push(char)
        num ++
      } else if (current.length > 1) {
        res.push(current.reduce((acc, cur) => acc += cur, ''))
        if (char == 1) {
          current = ['1']
          num = 2
        } else {
          current = []
          num = 1
        }
      } else if (current.length === 1) {
        current = []
        num = 1
      }
    }
    if (current.length > 1) {
      res.push(current.reduce((acc, cur) => acc += cur, ''))
    }
    return res
}

console.log(findSequential('31234121'))

You could do it this way:

function findSequential(str) {
  const res = [];
  let currentHigh = 0;
  for (let char of str) {
    if (+char === currentHigh + 1) {
      currentHigh++;
    } else if (currentHigh > 0) {
      res.push(buildSequence(currentHigh))
      currentHigh = +char === 1 ? 1 : 0;
    }
  }
  if (currentHigh > 0) {
    res.push(buildSequence(currentHigh));
  }
  return res;
}

function buildSequence(max) {
  if (max <= 1) { return "1"; }
  else { return buildSequence(max - 1) + max; }
}

console.log(findSequential("456000123456009123456780001234000"));
// ["123456", "12345678", "1234"]

console.log(findSequential("12"));
// ["12"]

console.log(findSequential("1212"));
// ["12", "12"]

console.log(findSequential("23"));
// []

Finally, i have this code for you

var str = "456000123456009123456780001234000";
var length = str.length;
var out= "";

for(i = 0; i < length; i++){
	if(str[i] == 1){
		out += str[i];
		var j = i;
		do{		
			j++;
			out += str[j];
		} while(str[j + 1] > out[out.length - 1])
		out += " ";
	}
}

console.log(out);	// Outputs: 123456 12345678 1234

very simple and short code

s= "456000123456009123456780001234000"
    var p
    var r=''
    for(let n of s ){
      if(n==1||n-p==1){
        r+=n, p=n
        r.length>1&&r.charAt(r.length-1)==1?r=r.substring(0,r.length-1)+'-1':r
      }
    }
    console.log(r.split('-'))

Here's a recursive version that keeps track of the index and length of the current sequence until it actually needs to output it, then calls substr. (Also useful to easily convert to returning just the sequences' locations in the string.)

function f(s, i=1, l=0){
  if (i == s.length)
    return l ? [s.substr(i-l, l)] : [];
    
  if (s[i] != Number(s[i-1]) + 1 && l)
    return [s.substr(i-l, l)].concat(f(s, i+1, 0));
    
  if (s[i] == 2 && s[i-1] == 1)
    return f(s, i+1, 2);
    
  return f(s, i+1, l ? l+1: 0);
}

var strs = [
  "456000123456009123456780001234000",
  "1212",
  "12",
  "23"
];

for (let s of strs){
  console.log(s);
  console.log(JSON.stringify(f(s)));
  console.log('');
}

发布评论

评论列表(0)

  1. 暂无评论