2025-08-20 17:15:03 +0000 UTC

Find the Longest Balanced Substring of a Binary String

Code

class Solution:
    def findTheLongestBalancedSubstring(self, s: str) -> int:
        res = 0
        cnt_0, cnt_1 = 0, 0
        for char in s:
            if char == "0":
                if cnt_1 != 0:
                    cnt_0 = 0
                cnt_0 += 1
                cnt_1 = 0
            else:
                cnt_1 += 1
                res = max(res, min(cnt_0, cnt_1) * 2)
        return res