# Count Binary Substrings

• can't understand.

• 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
``````

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

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

• 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
``````

• can't understand, it's too hard for a rookie

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