This is my code but the function countPalindromes
always returns 0 for some reason. I'm not able to understand why
bool isPalindrome(string s) {
int x=0;
int r= s.length() -1;
while(r>1){
if(s[x++]!=s[r--])
{
cout<<"Not Palindrome";
}
else
{
return true;
}
}
}
int countPalindromes(string s) {
int n= s.length();
int counter=0;
for(int i = 0; i<n ; i++)
{
for(int j=1; j< n -i ; j++)
{
if(isPalindrome(s.substr(i,j)=true))
{
counter+=1;
}
}
}
return counter;
}
int main() {
cout<<countPalindromes("ABA");
return 0;
}
There are lot of mistakes both in countPalindromes() and isPalindrome() function.
Just have a look at your modified code to understand.
bool isPalindrome(string s) {
int x=0;
int r= s.length() -1;
while(r>=0){
if(s[x++]!=s[r--])
{
//cout<<"Not Palindrome"<<endl;
return false;
}
}
return true;
}
int countPalindromes(string s) {
int n= s.length();
int counter=0;
for(int i = 0; i<n ; i++)
{
for(int j=1; j<= n -i ; j++)
{
if(isPalindrome(s.substr(i,j))==true)
{
counter+=1;
}
}
}
return counter;
}
int main() {
cout<<countPalindromes("ABA");
return 0;
}