Java Solution count Palindrome for each Index / T : O(N^2), S : O(1)


  • 0
    J
    public int countSubstrings(String s) {
            char[] chs = s.toCharArray();
            
            int count = 0;
            for(int i = 0; i < chs.length; i++){
                count += countPalindrome(i, i, chs);
                count += countPalindrome(i, i+1, chs);
            }
            
            return count;
        }
        
        public int countPalindrome(int i, int j, char[] chs){
            int count = 0;
            while(0 <= i && j < chs.length && chs[i--] == chs[j++]){
                count++;
            }
            return count;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.