提问人:Yooo dev 提问时间:10/2/2022 最后编辑:Amila SenadheeraYooo dev 更新时间:10/2/2022 访问量:543
查找字符串中的连续数字序列
Find consecutive numbers sequence in a string
问:
我有一串数字,其中总有一个随机序列,比如:
891011 -> 8, 9, 10, 11
123124 -> 123, 124
如何找到序列?我目前的代码是这样的:
var digits = [8, 9, 1, 0, 1, 1];
var number;
for (var j = 0; j < digits.length; j++) {
number = digits.slice(0, j + 1).join("");
if (
Number(number) === Number(digits.slice(j, number.length).join("")) &&
digits
.join("")
.match(new RegExp(".{1," + number.length + "}", "g"))
.every(function(num, index) {
return index === digits.length - 1 || num < digits[index + 1];
})
) {
break;
}
}
console.log(number)
答:
1赞
Amila Senadheera
10/2/2022
#1
您可以递增起始数字的位数,看看我们是否可以生成具有连续数字的匹配输出。尝试如下:
const findSequence = (input) => {
// starting number cannot be more than half of the length
let maxLengthOfStartingNumber = input.length / 2;
for(let i = 1; i <= maxLengthOfStartingNumber; i++) {
// starting number can be a number with a few digits
let startingNumber = parseInt(input.substring(0, i));
// data holder for consecutive numbers we generate
let generatedNumbers = [startingNumber]
// current string we create by concatinating generated numbers
let currentString = startingNumber.toString();
// we can generate integers until we surpass the length of the actual input and check
while(currentString.length < input.length){
const nextNumber = generatedNumbers[generatedNumbers.length-1]+1;
generatedNumbers.push(nextNumber)
currentString += nextNumber;
}
// check whether we could generate a string with consecutive numbers which matches with the input
if(currentString === input){
return generatedNumbers;
}
}
// input is invalid and return null
return null;
}
const testInputs = ["891011", "123124", "9991000", "123454"]
testInputs.forEach(testInput => {
console.log(findSequence(testInput));
})
评论