鏈接:https://leetcode-cn.com/problems/count-binary-substrings
給定一個字符串 s,計算具有相同數量0和1的非空(連續)子字符串的數量,並且這些子字符串中的所有0和所有1都是組合在一起的。
重複出現的子串要計算它們出現的次數。
示例 1 :
輸入: "00110011"
輸出: 6
解釋: 有6個子串具有相同數量的連續1和0:“0011”,“01”,“1100”,“10”,“0011” 和 “01”。
請注意,一些重複出現的子串要計算它們出現的次數。
另外,“00110011”不是有效的子串,因爲所有的0(和1)沒有組合在一起。
示例 2 :
輸入: "10101"
輸出: 4
解釋: 有4個子串:“10”,“01”,“10”,“01”,它們具有相同數量的連續1和0。
注意:
s.length 在1到50,000之間。
s 只包含“0”或“1”字符。
最終改進代碼如下:
/* 思路
遍歷字符串記錄以下幾個值
count 查找到的子串個數
count0 當前查找到的連續 0 個數, 用完置 0
count1 當前查找到的連續 1 個數, 用完置 0
group0 當前查找到的連續 0 的組數, 用完置 0 (1 正常情況)
group1 當前查找到的連續 1 的組數, 用完置 0 (1 正常情況)
改進, 上述方法需要區分第一個數字爲 0 或者爲 1
countf counts groupf groups
f-firsr 當前字符串第一個字符類型
s-second 當前字符串第二個字符類型
*/
int countBinarySubstrings(char * s){
int count = 0;
int countf = 0;
int counts = 0;
int groupf = 0;
int groups = 0;
char *cur = s;
while(*cur != '\0'){ // 該層遍歷整個字符串
while(*cur != '\0'){ // 該層遍歷當前查找子串
if(*cur == *s){
if(0 == groups){ groupf = 1; }
if(1 == groups){
count+=counts;
s+=countf;
cur = s;
break;
}
countf++; // 改進, 之前放在該段if 之前
}else{
counts++;
groups = 1;
if(counts == countf){
count+=countf;
s+=countf;
cur = s;
break;
}
}
cur++;
}
if(*cur == '\0'){s++; cur = s;} // 特殊情況,cur 查到了最後。
countf = 0;
counts = 0;
groupf = 0;
groups = 0;
}
return count;
}
版本–改進超出時間限制問題:
int countBinarySubstrings(char * s){
int count = 0;
int count0 = 0;
int count1 = 0;
int group0 = 0;
int group1 = 0;
char *cur = s;
while(*cur != '\0'){
char frist_c = *s;
if(frist_c == '0'){
while(*cur != '\0'){
if(*cur == '0'){
count0++;
if(0 == group1){ group0 = 1; }
if(1 == group1){ count0--; count+=count1; s+=count0; cur = s; break; }
}
if(*cur == '1'){
count1++;
group1 = 1;
if(count1 == count0){ count+=count0; s+=count0; cur = s; break; }
}
cur++;
}
}
if(frist_c == '1'){
while(*cur != '\0'){
if(*cur == '1'){
count1++;
if(0 == group0){ group1 = 1; }
if(1 == group0){ count1--; count+=count0; s+=count1; cur = s; break; }
}
if(*cur == '0'){
count0++;
group0 = 1;
if(count0 == count1){ count+=count1; s+=count1; cur = s; break; }
}
cur++;
}
}
if(*cur == '\0'){s++; cur = s;}
count0 = 0;
count1 = 0;
group0 = 0;
group1 = 0;
}
return count;
}
版本–暴力破解(超出時間限制):
int countBinarySubstrings(char * s){
int count = 0;
int count0 = 0;
int count1 = 0;
int group0 = 0;
int group1 = 0;
char *cur = s;
while(*cur != '\0'){
char frist_c = *s;
if(frist_c == '0'){
while(group0 <= 1 && group1 <=1 && *cur != '\0'){
if(*cur == '0'){
count0++;
if(0 == group1){ group0 = 1; }
if(1 == group1){ group0++; break; }
}
if(*cur == '1'){
count1++;
group1 = 1;
if(count1 == count0){ count++; break; }
}
cur++;
}
cur = ++s;
count0 = 0;
count1 = 0;
group0 = 0;
group1 = 0;
}
if(frist_c == '1'){
while(group1 <= 1 && group0 <=1 && *cur != '\0'){
if(*cur == '1'){
count1++;
if(0 == group0){ group1 = 1; }
if(1 == group0){ group1++; break; }
}
if(*cur == '0'){
count0++;
group0 = 1;
if(count0 == count1){ count++; break; }
}
cur++;
}
cur = ++s;
count0 = 0;
count1 = 0;
group0 = 0;
group1 = 0;
}
}
return count;
}