原题链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
参考题解:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
要求串里面要有0和1,0必须在1前面,0,1数量相等
要构造出一个新串,先数有多少个0再数有多少个1,统计完后计算长度,如果不符合条件min(cnt0,cnt1)会取0,比如1前面没有0,处理完后下一个新串cnt0和cnt1重新置0
- class Solution {
- public:
- int findTheLongestBalancedSubstring(string s) {
- int n = s.size();
- int i = 0;
- int res = 0;
- while (i < n) {
- int cnt0 = 0,cnt1 = 0;
- while (i < n && s[i] == '0' ) i++,cnt0++;
- while (i < n && s[i] == '1' ) i++,cnt1++;
- res = max(res, min(cnt0, cnt1) * 2);
- }
- return res;
- }
- };