ui設(shè)計(jì)技術(shù)培訓(xùn)學(xué)校手機(jī)管家一鍵優(yōu)化
2023-11-08每日一題
一、題目編號(hào)
2609. 最長(zhǎng)平衡子字符串
二、題目鏈接
點(diǎn)擊跳轉(zhuǎn)到題目位置
三、題目描述
給你一個(gè)僅由 0 和 1 組成的二進(jìn)制字符串 s 。
如果子字符串中 所有的 0 都在 1 之前 且其中 0 的數(shù)量等于 1 的數(shù)量,則認(rèn)為 s 的這個(gè)子字符串是平衡子字符串。請(qǐng)注意,空子字符串也視作平衡子字符串。
返回 s 中最長(zhǎng)的平衡子字符串長(zhǎng)度。
子字符串是字符串中的一個(gè)連續(xù)字符序列。
提示:
- 1 <= s.length <= 50
- ‘0’ <= s[i] <= ‘1’
四、解題代碼
class Solution {
public:int findTheLongestBalancedSubstring(string s) {int res = 0, n = s.size();vector<int> count(2);for (int i = 0; i < n; i++) {if (s[i] == '1') {count[1]++;res = max(res, 2 * min(count[0], count[1]));} else if (i == 0 || s[i - 1] == '1') {count[0] = 1;count[1] = 0;} else {count[0]++;}}return res; }
};
五、解題思路
(1) 計(jì)數(shù)