2609.最长平衡子字符串
链接:2609.最长平衡子字符串
难度:Easy
标签:字符串
简介:给你一个仅由 0 和 1 组成的二进制字符串 s 。 如果子字符串中 所有的 0 都在 1 之前 且其中 0 的数量等于 1 的数量,则认为 s 的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。 返回 s 中最长的平衡子字符串长度。
题解 1 - python
- 编辑时间:2023-04-02
- 执行用时:36ms
- 内存消耗:15MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def findTheLongestBalancedSubstring(self, s: str) -> int:
        cnt0 = cnt1 = res = 0
        for i in range(len(s)):
            c = s[i]
            if c == '0':
                cnt0 += 1
            else:
                cnt1 += 1
                if cnt0 >= cnt1:
                    res = max(res, cnt1*2)
                if i + 1 == len(s) or s[i+1] == '0':
                    cnt0 = cnt1 = 0
        return res
题解 2 - cpp
- 编辑时间:2023-04-02
- 内存消耗:6MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
   public:
    int findTheLongestBalancedSubstring(string s) {
        int cnt0 = 0, cnt1 = 0, res = 0;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '0') {
                cnt0++;
            } else {
                cnt1++;
                if (cnt0 >= cnt1) {
                    res = max(res, cnt1 * 2);
                }
                if (i + 1 == s.size() || s[i + 1] == '0') {
                    cnt0 = cnt1 = 0;
                }
            }
        }
        return res;
    }
};
题解 3 - python
- 编辑时间:2023-11-08
- 执行用时:44ms
- 内存消耗:15.48MB
- 编程语言:python
- 解法介绍:一次遍历。
class Solution:
    def findTheLongestBalancedSubstring(self, s: str) -> int:
        n = len(s)
        i = ans = 0
        while i < n and s[i] == '1': i += 1
        while i < n:
            cur = i
            while i < n and s[i] == '0': i += 1
            cnt0 = i - cur
            while i < n and s[i] == '1': i += 1
            cnt1 = i - cur - cnt0
            ans = max(ans, min(cnt0, cnt1) * 2)
        return ans
题解 4 - rust
- 编辑时间:2023-04-02
- 内存消耗:2MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn find_the_longest_balanced_substring(s: String) -> i32 {
        let s = s.chars().collect::<Vec<char>>();
        let (mut cnt0, mut cnt1, mut res) = (0, 0, 0);
        for i in 0..s.len() {
            if s[i] == '0' {
                cnt0 += 1
            } else {
                cnt1 += 1;
                if cnt0 >= cnt1 {
                    res = res.max(cnt1 * 2)
                }
                if i + 1 == s.len() || s[i + 1] == '0' {
                    cnt0 = 0;
                    cnt1 = 0;
                }
            }
        }
        res
    }
}