原始问题:
python判断01串中不含110的最长子串长度
要判断一个01串中不含110的最长子串长度,可以使用滑动窗口的方法。具体步骤如下:
- 初始化两个指针left和right,分别表示窗口的左右边界。
- 使用一个字典count来记录窗口内每个字符出现的次数。
- 当right指针向右移动时,将count[窗口内的字符]加1。
- 当count['1'] + count['0'] + count['1'] == 2时,说明窗口内可能包含110,此时需要移动left指针,直到count['1'] + count['0'] + count['1'] != 2。
- 在移动left指针的过程中,不断更新最长子串的长度。
以下是实现这个算法的Python代码:
def longest_substring_without_110(s):
n = len(s)
left, right = 0, 0
max_len = 0
count = {'0': 0, '1': 0}
while right < n:
count[s[right]] += 1
if count['1'] + count['0'] + count['1'] == 2:
while count['1'] + count['0'] + count['1'] != 2:
count[s[left]] -= 1
left += 1
max_len = max(max_len, right - left + 1)
right += 1
return max_len例如,对于输入字符串"00110",函数返回的结果为3,因为最长的不含110的子串是"00"。
Prev:小明痴迷编程爱01,因怕警察惧110:求不含110的最长01子串长度