【题目】
给定一个字符串 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”字符。
【代码】
【C++】
执行用时:
28 ms, 在所有 C++ 提交中击败了58.45%的用户
内存消耗:
13.8 MB, 在所有 C++ 提交中击败了33.03%的用户
class Solution {
public:
int countBinarySubstrings(string s) {
vector<int> fenduan;
char first=s[0];
int loop=0;
for(int i=0;i<s.size();i++){
if(s[i]==first)
loop++;
else{
if(first=='1')
first='0';
else
first='1';
fenduan.push_back(loop);
loop=1;
}
}
fenduan.push_back(loop);
loop=0;
for(int i=1;i<fenduan.size();i++)
loop+=min(fenduan[i],fenduan[i-1]);
return loop;
}
};
【Python3】
执行用时:
208 ms, 在所有 Python3 提交中击败了44.06%的用户
内存消耗:
15.1 MB, 在所有 Python3 提交中击败了30.25%的用户
class Solution:
def countBinarySubstrings(self, s: str) -> int:
counts=list()
first=s[0]
cnt=0
for x in s:
if x==first:
cnt+=1
else:
first=str(1-int(first))
counts.append(cnt)
cnt=1
counts.append(cnt)
cnt=0
for i in range(1,len(counts)):
cnt+=min(counts[i],counts[i-1])
return cnt