For each char, we will go 1 to left and 1 to right, if the chars match, that is 1 substring:
For eg. s[1] is palindrome, as it is just 1 char. Now, we go left or right. As, s[0] and s[2] are same chars, s[0:2] is now a palindrome as well. But this approach gives us odd length palindrome.
To, get even length palindrome, we have to take 2 chars, with left pointer being L and Right pointer being L+1.
classSolution {
publicintcountSubstrings(String s) {
int ans = 0;
int n = s.length();
char[] arr = s.toCharArray();
int l,r;
l = r = 0;
for (int i = 0; i < n; i++) {
// odd length l = r = i;
while(l >= 0 && r < n && arr[l]==arr[r]){
ans += 1;
l--;
r++;
}
// even length l = i;
r = i + 1;
while(l >= 0 && r < n && arr[l]==arr[r]){
ans += 1;
l--;
r++;
}
}
return ans;
}
}
classSolution:
defcountSubstrings(self, s: str) -> int:
ans =0 n = len(s)
arr = list(s)
for i in range(n):
# Odd length l = r = i
while l >=0and r < n and arr[l] == arr[r]:
ans +=1 l -=1 r +=1# Even length l = i
r = i +1while l >=0and r < n and arr[l] == arr[r]:
ans +=1 l -=1 r +=1return ans
publicintcountSubstrings(String s) {
int n = s.length();
boolean[][] dp =newboolean[n][n]; // DP table to track palindromic substringsint count = 0;
// Base case: Single character substrings are always palindromesfor (int i = 0; i < n; i++) {
dp[i][i]=true;
count++;
}
// Base case: Two consecutive characters are palindromes if they are the samefor (int i = 0; i < n - 1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
dp[i][i + 1]=true;
count++;
}
}
// General case: Substrings of length >= 3for (int length = 3; length <= n; length++) { // length goes from 3 to nfor (int i = 0; i <= n - length; i++) { // Starting index of the substringint j = i + length - 1; // Ending index of the substring// A substring is a palindrome if its first and last characters match,// and the substring without them is also a palindromeif (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {
dp[i][j]=true;
count++;
}
}
}
return count;
}
defcountSubstrings(s: str) -> int:
n = len(s)
dp = [[False] * n for _ in range(n)] # DP table to track palindromic substrings count =0# Base case: Single character substrings are always palindromesfor i in range(n):
dp[i][i] =True count +=1# Base case: Two consecutive characters are palindromes if they are the samefor i in range(n -1):
if s[i] == s[i +1]:
dp[i][i +1] =True count +=1# General case: Substrings of length >= 3for length in range(3, n +1): # length goes from 3 to nfor i in range(n - length +1): # Starting index of the substring j = i + length -1# Ending index of the substring# A substring is a palindrome if its first and last characters match,# and the substring without them is also a palindromeif s[i] == s[j] and dp[i +1][j -1]:
dp[i][j] =True count +=1return count