Very Simple Java Solution with Detail Explanation

• A very easy explanation with an example
Lets take a string "aabaa"

Step 1: Start a for loop to point at every single character from where we will trace the palindrome string.
checkPalindrome(s,i,i); //To check the palindrome of odd length palindromic sub-string
checkPalindrome(s,i,i+1); //To check the palindrome of even length palindromic sub-string

Step 2: From each character of the string, we will keep checking if the sub-string is a palindrome and increment the palindrome count. To check the palindrome, keep checking the left and right of the character if it is same or not.

First Loop:

Palindrome: a (Count=1)

Palindrome: aa (Count=2)

Second Loop:

Palindrome: a (Count=3)

Palindrome: No Palindrome

Third Loop:

Palindrome: b,aba,aabaa (Count=6)

Palindrome: No Palindrome

Forth Loop:

Palindrome: a (Count=7)

Palindrome: aa (Count=8)

Count = 9 (For the last character)

'''

``````int count =1;
public int countSubstrings(String s) {
if(s.length()==0)
return 0;
for(int i=0; i<s.length()-1; i++){
checkPalindrome(s,i,i);     //To check the palindrome of odd length palindromic sub-string
checkPalindrome(s,i,i+1);   //To check the palindrome of even length palindromic sub-string
}
return count;
}

private void checkPalindrome(String s, int i, int j) {
while(i>=0 && j<s.length() && s.charAt(i)==s.charAt(j)){    //Check for the palindrome string
count++;    //Increment the count if palindromin substring found
i--;    //To trace string in left direction
j++;    //To trace string in right direction
}
}
``````

'''

• Thanks for your great explanation!

• The initial value of count should be 0.The solution doesn't get accepted if it is 1

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.