[LeetCode] 2609. Find the Longest Balanced Substring of a Binary String
You are given a binary string s consisting only of zeroes and ones.
A substring of s is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.
Return the length of the longest balanced substring of s.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "01000111"
Output: 6
Explanation: The longest balanced substring is "000111", which has length 6.
Example 2:
Input: s = "00111"
Output: 4
Explanation: The longest balanced substring is "0011", which has length 4.
Example 3:
Input: s = "111"
Output: 0
Explanation: There is no balanced substring except the empty substring, so the answer is 0.
Constraints:
1 <= s.length <= 50
'0' <= s[i] <= '1'
最长平衡子字符串。
给你一个仅由 0 和 1 组成的二进制字符串 s 。
如果子字符串中 所有的 0 都在 1 之前 且其中 0 的数量等于 1 的数量,则认为 s 的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。
返回 s 中最长的平衡子字符串长度。
子字符串是字符串中的一个连续字符序列。
思路
这里我提供一个双指针的做法。对于每个 index (i, i + 1),我们把位置 i 上的字母当做 0,把位置 i + 1 上的字母当做 1,看看往左往右能同时延伸多长。这个思路借鉴了从中间往两边找最长回文子串的思路。
复杂度
时间O(n^2) - worst case
空间O(1)
代码
Java实现
class Solution { int res = 0; public int findTheLongestBalancedSubstring(String s) { for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) == '0') { helper(s, i, i + 1, '0', '1'); } } return res; } private void helper(String s, int left, int right, char charLeft, char charRight) { while (left >= 0 && right < s.length() && s.charAt(left) == charLeft && s.charAt(right) == charRight) { left--; right++; } res = Math.max(res, right - left - 1); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2022-11-08 [LeetCode] 1544. Make The String Great
2022-11-08 [LeetCode] 1323. Maximum 69 Number
2020-11-08 [LeetCode] 1634. Add Two Polynomials Represented as Linked Lists
2019-11-08 [LeetCode] 82. Remove Duplicates from Sorted List II
2019-11-08 [LeetCode] 83. Remove Duplicates from Sorted List
2019-11-08 [LeetCode] 19. Remove Nth Node From End of List