Count Binary Substrings


  • 1

    Click here to see the full article post


  • 0
    J

    can't understand.


  • 0
    M

    My elementary solution's not as beautiful:

    class Solution(object):
        def countBinarySubstrings(self, s):
            ans=0
            count=[0,0]
            i=0
            while i<len(s):
                count[0]=0
                while i<len(s) and s[i]==s[0]:
                    count[0]+=1
                    i+=1
                ans+=min(count[0],count[1])
                count[1]=0
                while i<len(s) and s[i]!=s[0]:
                    count[1]+=1
                    i+=1
                ans+=min(count[0],count[1])
            return ans
    

  • 0

  • 0
    M

    How come that using Pattern.matches from java.util.regex.Pattern gives me a compilation error?
    "Line 7: error: cannot find symbol: variable Pattern"


  • 0
    Y

    beat my solution !class Solution {
    public:
    int countBinarySubstrings(string s) {
    int count(0), nextn(0), pren(0);
    for(int i=0; i<s.size(); ++i)
    {
    nextn = 1;
    while(i+1<s.size() && s[i]==s[i+1]){++nextn; ++i;}
    count += min(pren, nextn);
    pren = nextn;
    }
    return count;
    }
    };


  • 0
    W

    My two pointer solution:

    class Solution(object):
        def countBinarySubstrings(self, s):
            """
            :type s: str
            :rtype: int
            """
            res = 0
            for i in range(0, len(s)-1):
                if s[i] != s[i+1]:
                    res += self.helper(i, s)
            return res
        
        def helper(self, i, s):
            count = 1
            while i-count >= 0 and i+1+count < len(s) and s[i-count] == s[i] and s[i+1+count] == s[i+1]:
                count += 1
            return count
    

Log in to reply
 

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