Special String Again

  • + 4 comments

    Tried to simplify the code above and optimize a little bit by avoiding iterating over the repeatable symbols and jumping straight to the distinct by incrementing for loop counter and replacing sum with n*(n+1)/2

    public static long substrCount(int length, String s) {
    	long counter = 0;
    	for (int i = 0; i < length; i++) {
    		// if the current symbol is in the middle of palindrome, e.g. aba
    		int offset = 1;
    		while (i - offset >= 0 && i + offset < length && s.charAt(i - offset) == s.charAt(i - 1)
    				&& s.charAt(i + offset) == s.charAt(i - 1)) {
    			counter++;
    			offset++;
    		}
    		// if this is repeatable characters aa
    		int repeats = 0;
    		while (i + 1 < length && s.charAt(i) == s.charAt(i + 1)) {
    			repeats++;
    			i++;
    		}
    		counter += repeats * (repeats + 1) / 2;
    	}
    	return counter + length;
    }