1. class Solution {
  2. /**
  3.   A palindromic substring expands symmetrically from its center.
  4.   Every palindrome has a center
  5.   A string of length n has 2n − 1 possible centers
  6.  
  7.   For each index i, we consider:
  8.   ✅ Odd-length palindrome
  9.   Center at i
  10.   Example: "aba"
  11.  
  12.   ✅ Even-length palindrome
  13.   Center between i and i+1
  14.   Example: "abba"
  15.  
  16.   Expand Around Center
  17.   For each center:
  18.   Move left pointer → left--
  19.   Move right pointer → right++
  20.   Continue while:
  21.   Characters match
  22.   Indices are valid
  23.   Each valid expansion = 1 palindrome, so do count
  24.  
  25.   Count All Palindromes
  26.   Loop through all indices:
  27.   At each index:
  28.   Count odd palindromes
  29.   Count even palindromes
  30.   Add both to total
  31.   Return Result
  32.   Total count gives all palindromic substrings.
  33.   */
  34. public int countSubstrings(String s) {
  35. int count = 0;
  36. for(int i=0; i<s.length(); i++)
  37. {
  38. int oddLength = countPalindromes(s, i, i);
  39. int evenLength = countPalindromes(s, i, i+1);
  40. count += (oddLength + evenLength);
  41. }
  42. return count;
  43. }
  44.  
  45. public int countPalindromes(String s, int left, int right)
  46. {
  47. int count = 0;
  48. while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right))
  49. {
  50. count++;
  51. left--;
  52. right++;
  53. }
  54. return count;
  55. }
  56. }