刷题 DAY4 求最长平衡子字符串 C++

答案如下:

#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指针移到最后一位。

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值