skip to Main Content

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


  1. In the iteration following a slice – i will be equal to start, 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 incrementing i when you do a slice.

    function splitSandwichedLetters(str) {
      const result = [];
      let start = 0;
    
      for (let i = 1; i < str.length; i++) {
        if (str[i] === str[start]) {
          result.push(str.slice(start, i + 1));
          start = i + 1; // this means that next iteration i will be equal to start
          i++; // so increment i to avoid that
        }
      }
    
      if (start < str.length) {
        result.push(str.slice(start));
      }
    
      return result;
    }
    
    // Test 
    const str1 = "abbabbabba";
    
    
    console.log(splitSandwichedLetters(str1));
    Login or Signup to reply.
  2. Keep track of the first char, keep a sub word, and a list of the result words:

    const splitter = (word) => {
      const ans = [];
    
      let first_char = '';
      let sub_word = '';
    
      for (const c of word) {
        sub_word += c;
    
        if (c === first_char) {
          ans.push(sub_word);
          sub_word = '';
          first_char = '';
        } else if (first_char === '') {
          first_char = c;
        }
      }
    
      if (sub_word !== '') {
        ans.push(sub_word); // last hanging bit
      }
    
      return ans;
    }
    
    console.log(splitter('abbbaba')); // [ 'abbba', 'ba' ]
    console.log(splitter('bbbabaa')); // [ 'bb', 'bab', 'aa' ]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search