I wanted to function a function that does this:
const input =“hellooooloo”;
const results = getRepeated(input);
console.log(results) // [(2,3), (4,7), (9,10)]
It returns an array of arrays of indices of the starting and ending index of consecutively repeated chars from a string.
Here is my attempt, it is a O(n^2). I wonder if there is a more elegant and efficient way of achieving this
const input = 'hellooooloo';
const results = getRepeated(input); // // [(2,3), (4,7), (9,10)]
function getRepeated(string) {
const results = []
if(string.length < 2) return results
for(let i = 0; i < string.length - 1; i++) {
if(i > 1 && string[i] === string[i-1]) {
continue
}
let startIndex = i
let endIndex = i
for(let j = i + 1; j < string.length; j++) {
if(string[i] === string[j]) {
endIndex = j
} else {
break
}
}
if(startIndex !== endIndex) {
results.push([startIndex, endIndex])
}
}
return results
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…