[leetcode]696. Count Binary Substrings
Analysis
周五~—— [ummmm~]
Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0’s and 1’s, and all the 0’s and all the 1’s in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Implement
TLE……………………..
class Solution {
public:
int countBinarySubstrings(string s) {
int len = s.length();
int len1, len0;
int res = 0;
bool find;
for(int i=0; i<len; i++){
len0 = len1 = 0;
int j = i+1;
find = false;
if(s[i] == '0'){
len0++;
while(s[i] == s[j] && j<len){
len0++;
j++;
}
while(s[j] == '1' && j<len){
len1++;
j++;
if(len1 == len0){
find = true;
break;
}
}
}
else{
len1++;
while(s[i] == s[j] && j<len){
len1++;
j++;
}
while(s[j] == '0' && j<len){
len0++;
j++;
if(len1 == len0){
find = true;
break;
}
}
}
if(find)
res++;
}
return res;
}
};
把“1111000011010001011”转化为“4 4 2 1 1 3 1 1 2 ”, 然后进行统计~
class Solution {
public:
int countBinarySubstrings(string s) {
int len = s.length();
int pre, cur;
int res = 0;
cur = 1;
pre = 0;
for(int i=1; i<len; i++){
if(s[i] == s[i-1])
cur++;
else{
pre = cur;
cur = 1;
}
if(cur <= pre)
res++;
}
return res;
}
};