Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- /**
- A palindromic substring expands symmetrically from its center.
- Every palindrome has a center
- A string of length n has 2n − 1 possible centers
- For each index i, we consider:
- ✅ Odd-length palindrome
- Center at i
- Example: "aba"
- ✅ Even-length palindrome
- Center between i and i+1
- Example: "abba"
- Expand Around Center
- For each center:
- Move left pointer → left--
- Move right pointer → right++
- Continue while:
- Characters match
- Indices are valid
- Each valid expansion = 1 palindrome, so do count
- Count All Palindromes
- Loop through all indices:
- At each index:
- Count odd palindromes
- Count even palindromes
- Add both to total
- Return Result
- Total count gives all palindromic substrings.
- */
- int count = 0;
- for(int i=0; i<s.length(); i++)
- {
- int oddLength = countPalindromes(s, i, i);
- int evenLength = countPalindromes(s, i, i+1);
- count += (oddLength + evenLength);
- }
- return count;
- }
- {
- int count = 0;
- while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right))
- {
- count++;
- left--;
- right++;
- }
- return count;
- }
- }
RAW Paste Data
Copied
