Leetcode 647) Palindromic Substrings

image

My Answer

class Solution {
    public int countSubstrings(String s) {
        //Center will be the pivot.
        int numPal = s.length();//Each character is considered as one palindromic substring.
        for(int i =0;i<s.length();i++){
            int left=i-1;
            int right=i+1;
            //Odd number
            while(left>=0 && right <s.length() && s.charAt(left)==s.charAt(right)){
                numPal++;
                left--;
                right++;
            }

            //Even number
            left=i;
            right=i+1;
            while(left>=0 && right<s.length() &&  s.charAt(left)==s.charAt(right)){
                numPal++;
                left--;right++;
            }
        }
        return numPal;
    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2