C++中计算二进制子字符串
假设我们有一个字符串s,我们必须找到具有相同数量的0和1的连续子字符串的计数,并且这些子字符串中的所有0和所有1都被连续分组。如果子字符串出现多次,则计算它们出现的次数。
因此,如果输入类似于“11001100”,则输出将为6,因为子字符串为“1100”,“10”,“0011”,“01”,“1100”,“10”。
为了解决这个问题,我们将遵循以下步骤-
定义大小为2的数组cnt,并用0填充
res:=0
对于初始化i:=0,当i<s的长度时,更新(将i增加1),执行-
(将res增加1)
cnt[num]:=0
num:=s[i]-ASCII'0'
如果i等于0或s[i]不等于s[i-1],则-
(将cnt[num]增加1)
如果cnt[num]<=cnt[1-num],则-
返回资源
让我们看下面的实现以更好地理解-
示例
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countBinarySubstrings(string s) {
int cnt[2] = { 0 };
int res = 0;
for (int i = 0; i < s.length(); ++i) {
int num = s[i] - '0';
if (i == 0 || s[i] != s[i - 1])
cnt[num] = 0;
++cnt[num];
if (cnt[num] <= cnt[1 - num])
++res;
}
return res;
}
};
main(){
Solution ob;
cout << (ob.countBinarySubstrings("11001100"));
}输入项
"11001100"
输出结果
6
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬