LeetCode周赛链接:
难度简单4
给你一个仅由
0
和1
组成的二进制字符串s
。如果子字符串中 所有的
0
都在1
之前 且其中0
的数量等于1
的数量,则认为s
的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。返回
s
中最长的平衡子字符串长度。子字符串是字符串中的一个连续字符序列。
思路:类似于滑动窗口
class Solution {
public:
int findTheLongestBalancedSubstring(string s) {
int t=0,tt=0,max1=0;
for(int i=0;i<s.length();i++)
{
if(s[i]=='0'&&tt!=0)//重置
{
t=0,tt=0;
t++;
}
else if(s[i]=='0')t++;
else if (s[i]=='1')tt++;
if(t>=tt)max1=max(max1,tt*2);
}
return max1;
}
};