答案如下:
#include<iostream>
#include<algorithm>
using namespace std;
#include<string>
class Solution {
public:
int pinghengzizifuchuan(string s) {
int left = 0, right = 0, num_one = 0, num_zero = 0, res = 0;
while (right < s.length()) {
if (s[right] == '0') num_zero++;
else num_one++;
while (((num_one > num_zero) || (num_zero > num_one && s[right] == '0' && num_one != 0) || (right = s.length()-1 && num_zero > num_one)) && left <= right) {
if (s[left] == '0') num_zero--;
else num_one--;
left++;
}
if (num_one == num_zero && num_one > 0) res = max(res, num_zero + num_one);
right++;
}
return res;
}
};
int main() {
Solution a;
string s;
cin >> s;
int longest = a.pinghengzizifuchuan(s);
cout <<longest << endl;
return 0;
}
当右边界小于字符串的长度时进入循环。
当字符串不是平衡字符串时进入第二层循环(条件为:数字1的数量大于数字0的数量或(0的数量大于1的数量且右边界的值为0且数字1的数量不为0)或(右边界到了字符串的长度且数字0的数量大于1的数量)且左边界小于等于右边界)
随后判断左边界是否为0,将left指针右移
判断当前是否为平衡字符串 取字符串的长度 随后将right指针右移。
注意:right指针的右移是为了找到最大的平衡子字符串,直到right指针移到最后一位。