1. 题目描述
2. 标准答案
统计相邻0、1的故事,
- 方法一:按字符分组
思路与算法
我们可以将字符串 s 按照 0和 1 的连续段分组,存在 counts数组中,例如 s=00111011,可以得到这样的counts 数组: counts={2,3,1,2}。
这里 counts 数组中两个相邻的数一定代表的是两种不同的字符。假设 counts 数组中两个相邻的数字为 u 或者 v,它们对应着 u 个 0和 v 个 1,或者 u 个 1 和 v个 0。它们能组成的满足条件的子串数目为 min{u,v},即一对相邻的数字对答案的贡献。
我们只要遍历所有相邻的数对,求它们的贡献总和,即可得到答案。
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/count-binary-substrings/solution/ji-shu-er-jin-zhi-zi-chuan-by-leetcode-solution/
来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
int countBinarySubstrings(string s) {
vector<int> counts;
int ptr = 0, n = s.size();
while (ptr < n) {
char c = s[ptr];
int count = 0;
while (ptr < n && s[ptr] == c) {
++ptr;
++count;
}
counts.push_back(count);
}
int ans = 0;
for (int i = 1; i < counts.size(); ++i) {
ans += min(counts[i], counts[i - 1]);
}
return ans;
}
};
3. 垃圾的我
从头开始遍历,依次过滤掉一个;分析剩余最大子串。问题出现在特长的字符串会多次拷贝,浪费空间与时间,简单的字符串处理没问题。
class Solution {
public:
int countBinarySubstrings(string s) {
int res = 0;
for(int i=0;i<s.size();i++)
{
if(isZi(s.substr(i,s.size()-i)))
res++;
}
return res;
}
bool isZi(string s)
{
char infer = s[0];
int num1=1;
bool ischanged = false;
int i=1;
for(;i<s.size() ;i++)
{
if(s[i] == infer)
num1++;
else
break;
}
int j=i;
int num2 = 0;
for(;j<s.size() && num2 != num1;j++)
{
if(s[j] == !(infer-'0')+'0')
num2++;
else
break;
}
if(num1 == num2)
return true;
return false;
}
};
4. 二次修改答案
class Solution {
public:
int countBinarySubstrings(string s) {
if (s.size()==0 ||s.size()==1 )
return 0;
vector<int> counts;
int i=0;
int j;
for(;i<s.size();)
{
char refer = s[i];
for(j=i+1;j<s.size();j++)
{
if(s[j] != refer)
{
counts.push_back(j-i);
break;
}
}
if(j==s.size() && counts.size()!=0)
{counts.push_back(j-i);2
}
i=j;
}
int res = 0;
if (counts.size()==1)
return counts[0];
else
for (int index=1;index<counts.size();index++)
{
res+=min(counts[index-1], counts[index]);
}
return res;
}
};