给定一个字符串 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
int countBinarySubstrings(char* s)
{
int n=strlen(s);
int* temp=(int*)malloc(sizeof(int)*n);
int k=0;
int count=1;
int res=0;
for(int i=1;i<n;i++)
{
if(s[i]==s[i-1])
{
count++;
}
else
{
temp[k++]=count;
count=1;
}
}
temp[k]=count;
for(int i=1;i<=k;i++)
{
if(temp[i]<temp[i-1])
{
res+=temp[i];
}
else
{
res+=temp[i-1];
}
}
return res;
}
C++
class Solution {
public:
int countBinarySubstrings(string s)
{
int n=s.length();
int count=1;
vector<int> temp;
int res=0;
for(int i=1;i<n;i++)
{
if(s[i]==s[i-1])
{
count++;
}
else
{
temp.push_back(count);
count=1;
}
}
temp.push_back(count);
for(int i=1;i<temp.size();i++)
{
res+=min(temp[i],temp[i-1]);
}
return res;
}
};
python
class Solution:
def countBinarySubstrings(self, s):
"""
:type s: str
:rtype: int
"""
n=len(s)
temp=[]
count=1
res=0
for i in range(1,n):
if s[i]==s[i-1]:
count += 1
else:
temp.append(count)
count=1
temp.append(count)
for i in range(1,len(temp)):
res += min(temp[i],temp[i-1])
return res