Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

JavaScript algorithms: find starting and ending indices of consecutively repeated chars from a string

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'd use a regular expression: match and capture one character, then backreference that same character as many times as you can. Perform a global regex match on the string. Take all the matches and map them to an array of their index, and their index plus the length of the match:

const getRepeated = str => [...str.matchAll(/(.)1+/g)]
  .map(({ index, 0: match }) => [index, index + match.length - 1]);

const input = "hellooooloo";
const results = getRepeated(input);
console.log(results) // [(2,3), (4,7), (9,10)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...