这一道题直接做,O(n^3), 枚举所有子串,验证合法性
关键是理解具有相同数量的连续1和0非常关键。
统计出连续的0和1区间段,然后就能找出答案。利用滚动数组可以将时间优化到O(1)
class Solution {
public:
int countBinarySubstrings(string s) {
vector<int> help;
int n = s.size(), i = 0;
while(i<n){
char c = s[i];
int count = 0;
while(i<n&&s[i]==c){
i++;
count++;
}
help.push_back(count);
}
int res = 0;
for(int i=0;i<help.size()-1;i++){
res+=min(help[i],help[i+1]);
}
return res;
}
};