Search code examples
c++stringsubstringpalindrome

Program to find the number of substrings that are palindromes in a given string


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;
}

Solution

  • There are lot of mistakes both in countPalindromes() and isPalindrome() function.

    1. Firstly in isPalindrome() function, you are checking until r>1. You have to check the whole string. For that the condition will be r>=0. You are returning true whenever there is a character match. You can return true after becoming sure that any character at position S[i] is not equal to S[n-i-1] (where n is length of the string).
    2. Secondly is countPalindromes() function you are passing wrong argument when comparing substring.

    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;
    }