我将在从 1 开始的字符串中找到连续的数字字符串。例如,我有这个字符串。
"456000123456009123456780001234000"
这里的顺序字符串将是
"123456", "12345678", "1234"
如何有效地使用 Javascript 获得上述结果?
代码看起来像这样。
findSequential("456000123456009123456780001234000");
//expected output
"123456", "12345678", "1234"
***注意:“1”本身不是连续的,例如:
"3938139" - has no sequence
"39381249" - has "12"
任何语言的解决方案都会受到赞赏,但更喜欢 Javascript 或 C。
谢谢你的帮助!
最佳答案
一个简单的 for 循环应该能够实现这一点。在 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'))
关于javascript - 使用javascript在字符串中查找顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62461225/