Special String Again

  • + 0 comments

    JS - fast

    function substrCount(n, s) {
      let _specials = 0;
    
      const charr = [...s];
      for (let i = 0; i < n; i++) {
        let specialChar = charr[i];
        let nextCharIdx = i + 1;
    
        let isSpecial = true;
        while (isSpecial) {
          const nextChar = charr[nextCharIdx];
    
          if (!nextChar) break; // eol
    
          // check if same char => special (e.g. 'aa' or 'aaa')
          if (nextChar === specialChar) {
            _specials++;
            nextCharIdx++;
          } else {
            // check for substring with 'special middle char' (e.g. 'aabaa')
            const length = nextCharIdx - i;
            if (nextCharIdx + 1 + length <= n) { // check eol
              const afterStr = s.substring(nextCharIdx + 1, nextCharIdx + 1 + length);
              if ([...afterStr].every((c) => c === specialChar)) {
                _specials++;
              }
            }
            isSpecial = false;
          }
        }
      }
    
      return _specials + n;
    }