Special String Again

  • + 0 comments
        static int palindromHalfLength(int i, String s) {
            int step = 1;
            char palChar = s.charAt(i-1);
            while (i-step>=0 && i+step<s.length()
                    && s.charAt(i-step) == palChar
                    && s.charAt(i+step) == palChar) step++;
    
            return step-1;
        }
        // Complete the substrCount function below.
        static long substrCount(int n, String s) {
            if (s.length() == 0) return 0;
            long res = 1;
            int countSimChar = 1;
            for (int i = 1; i < s.length(); i++) {
                if (s.charAt(i-1) == s.charAt(i)) {
                    countSimChar++;
                }  else {
                    res += palindromHalfLength(i, s);
                    countSimChar = 1;
                }
                res += countSimChar;
            }
            return res;
        }
    

    If there are k similar characters in a raw, number of palindroms will be 1+2+..+k; If current character differs from the prvious one it might also be a palindrom, and half length of the palindrom would be the number of palindroms: aaacaaa -> half length is 3 and there are 3 palindroms: aca, aacaa, aaacaaa