C++ soln with comments

  • 0
    class Solution {
        // Scan through all lengths and check if palindrome 
        // and increment the count 
        // For eg: Check for lenghts 0,1,2..N, and for each
        // length check how many palindrome exists.
        bool checkPalin(string str, int s , int e){
            while(s <= e){
                if(str[s++]!=str[e--]) return false;
            return true;
        int countSubstrings(string str) {
            if(str.length() == 0) return 0;
            int size = str.length();
            int sum=0;
            for(int len = 0; len<size ; ++len){
                for(int s=0 ; s<size-len ;++s){
                    // If palin for this specific start and
                    // end point increment the count.
                    if(checkPalin(str, s, s+len)) sum++;          
            return sum;

Log in to reply

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