congr / world

2 stars 1 forks source link

LeetCode : 647. Palindromic Substrings #454

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/palindromic-substrings/

image

congr commented 5 years ago

O(N^2)

class Solution {
    public int countSubstrings(String s) {
        int count = 0;

        for (int i = 0; i<s.length(); i++) {
            count += expandPal(s, i, i);
            count += expandPal(s, i, i+1);
        }    

        return count;
    }

    int expandPal(String s, int left, int right) {
        int count = 0;

        while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
            count++;
        }

        return count;
    }
}