aiaiask.com©

开花即结果 提问即答案

python判断01串中不含110的最长子串长度
原始问题:

python判断01串中不含110的最长子串长度

要判断一个01串中不含110的最长子串长度,可以使用滑动窗口的方法。具体步骤如下:

  1. 初始化两个指针left和right,分别表示窗口的左右边界。
  2. 使用一个字典count来记录窗口内每个字符出现的次数。
  3. 当right指针向右移动时,将count[窗口内的字符]加1。
  4. 当count['1'] + count['0'] + count['1'] == 2时,说明窗口内可能包含110,此时需要移动left指针,直到count['1'] + count['0'] + count['1'] != 2。
  5. 在移动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"。

python判断01串中不含110的最长子串长度
https://www.aiaiask.com/ask/46149.html
AI / 模型DeepSeek
时间 / DATESeptember 6, 2023, 9:25 PM
语言zh-CN
IP / 区域江苏 苏州