I have this string:
const str = "abbbaba";
I am looking for a way to split this string in groups of sandwiched letters, or all remaining letters.
Examples
My string should be split into this:
["abbba", "ba"]
Where "abbba" is the first substring because it starts and ends with an "a".
The last substring starts with a "b", but there is
no ending "b", so it just takes the rest of the string.
Another scenario:
const str2 = "bbbabaa"
It should be split like this:
["bb", "bab", "aa"]
Closest attempt
The following is my closest attempt for string "abbabbabba"
which returns
["abba", "bb", "a", "bb", "a"]
instead of
["abba", "bb", "abba"]
function splitSandwichedLetters(str) {
const result = [];
let start = 0;
for (let i = 1; i < str.length; i++) {
if (str[i] === str[start] && (i === str.length - 1 || str[i + 1] !== str[start])) {
result.push(str.slice(start, i + 1));
start = i + 1;
}
}
if (start < str.length) {
result.push(str.slice(start));
}
return result;
}
// Test
const str1 = "abbabbabba";
console.log(splitSandwichedLetters(str1)); // Output: ["abbba", "ba"]
2
Answers
In the iteration following a slice –
i
will be equal tostart
, and that breaks things because you’ll be checking to see if a letter is equal to itself instead of equal to a letter occurring later. Fix it by incrementingi
when you do a slice.Keep track of the first char, keep a sub word, and a list of the result words: