November 23, 2019

647. Palindromic Substrings

647. Palindromic Substrings

Expand Around Center, time = O(n^2), space = O(1).

class Solution {
    private int count = 0;
    public int countSubstrings(String s) {
        for (int i = 0; i < s.length(); i++) {
            checkPalindrome(s, i, i);
            checkPalindrome(s, i, i + 1);
        }
        return count;
    }
    
    private void checkPalindrome(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            count ++;
            left --;
            right ++;
        }
    }
}
comments powered by Disqus