2609. 最长平衡子字符串

题目链接:2609. 最长平衡子字符串

方法:模拟

解题思路

统计当前\(0\)\(1\)的数量\(cnt0\)\(cnt1\),如果当前字符为'\(0\)',且\(1\)的数量不为\(0\),说明\(0\)前面出现\(1\),则重置\(cnt0 = 1\)\(cnt1 = 0\)。每次计算当前的最大值。

代码

class Solution {
public:
    int findTheLongestBalancedSubstring(string s) {
        if (s.length() == 0) return 0;
        int n = s.length(), ans = 0;
        int cnt0 = 0, cnt1 = 0;
        for (int j = 0; j < n; j ++ ) {
            if (s[j] == '0' && cnt1) { // 0前面出现1,重置数量
                cnt0 = 1, cnt1 = 0;
                continue;
            }
            s[j] == '0' ? cnt0 ++ : cnt1 ++ ;
            ans = max(ans, min(cnt0, cnt1) * 2); // 取其中的最小值*2
        }
        return ans;
    }
};

复杂度分析

时间复杂度:\(O(n)\)
空间复杂度:\(O(1)\)

posted @ 2023-04-09 01:05  lixycc  阅读(43)  评论(0)    收藏  举报