How can I find the longest sequence of matching letters in a string?

Viewed 153

I'm new in JavaScript and I'm trying to find the max value of same letters in row. I have a number of letters in string but I don't know what to do next.

Will be grateful for help.

There is my code:

let myString = "aaaAAAwwwwkkaaaaalllkk"


function countLetters(myString){
    let lowcase = myString.toLowerCase();
    let tempArr = lowcase.split('');
    let letters = [];
    let count = 1;

    for(i = 0 ; i < tempArr.length; i++){
        if(tempArr[i] === tempArr[i+1]){
            count++;
        }
        else{
            let value = `${count},${tempArr[i]}`;
            letters = [...letters, value];
            count = 1;
        }
    }
    return letters
}
console.log(countLetters(myString))

2 Answers

You can use a regular expression to identify the chunks that have a repeating character:

function countLetters(myString) {
    return myString.toLowerCase()
                   .match(/(.)\1*/gs)
                   .reduce((acc, s) => s.length > acc.length ? s : acc, "");
}

let myString = "xxaaaAAAwwwwkkaaaaalllkk"
console.log(countLetters(myString))

This returns the (lowercased) longest substring that consists of the same (case-insensitive) character.

The key is to keep some state as you loop through the string (which is just an array of characters). We'll need to know what letter we're currently counting, and how many we've seen, plus the largest value we have seen.

As you loop through the array, if you find the same letter you've been processing, you increment the count. Otherwise, you first have to save the current count into the final result, then resetting the rest of the local state.

All together, it ends up like this:

function countLetters(myString) {
    let previous = '', // nothing matches this
        count = 0,
        result = { letter: '', count: 0 };

    for (const letter of myString.toLowerCase()) {
        if (letter === previous) {
            count++;
        }
        else {
            if (result !== null && count > result.count) {
                result = { letter: previous, count: count };
            }

            previous = letter;
            count = 1;
        }
    }

    return result;
}

Edited to return the letter that had the longest streak.

Related