Skip to content

Latest commit

 

History

History
53 lines (37 loc) · 820 Bytes

File metadata and controls

53 lines (37 loc) · 820 Bytes

Palindromic Substrings

Problem Link

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


Pattern

  • String
  • Two Pointer
  • DP

Approach

Count palindromes by expanding around each center (odd and even length).


Time Complexity

O(n^2)

Space Complexity

O(1)


Java Solution

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