C++: Like Longest Palindromic Substring (Approach #4)


  • 1

    This is pretty similar to checking for Longest Palindromic Substring (approach #4) expand around the center (https://leetcode.com/problems/longest-palindromic-substring/solution/#approach-4-expand-around-center-accepted):

    class Solution {
    public:
        int countLikePalindrome(string& s, int i, int j) {
            int ans=0;
            
            while(i>=0 && j<s.size() && s[i]=='0' && s[j]=='1') {
                ans++;
                i--;
                j++;
                if(s[i]=='1' && s[j]=='0')
                    return ans;
            }        
            
            while(i>=0 && j<s.size() && s[i]=='1' && s[j]=='0') {
                ans++;
                i--;
                j++;
                if(s[i]=='0' && s[j]=='1')
                    return ans;
            }
            
            return ans;
        }
        
        int countBinarySubstrings(string s) {
            if(s.empty())
                return 0;
            
            int ans=0;
            for(int i=0; i<s.size()-1; i++) {
                ans+=countLikePalindrome(s, i, i+1);
            }
            
            return ans;
        }
    };
    
    

Log in to reply
 

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