Leecode 3.無重複字符串

題目

在這裏插入圖片描述

題解

  1. 使用數組作爲容器–直觀的滑動窗口法
def lengthOfLongestSubstring(s: str) -> int:
    # 字符串爲空則返回零
    if not s:
        return 0
    res = []  # 滑動窗口數組
    max_length = 0  # 最長串長度
    # 遍歷字符串
    for x in s:
        # 如果字符不在滑動窗口中,則直接擴展窗口
        if x not in res:
            # 擴展窗口
            res.append(x)
        # 如果字符在滑動窗口中,則
        # 1. 從窗口中移除重複字符及之前的字符串部分
        # 2. 再擴展窗口
        else:
            # 從窗口中移除重複字符及之前的字符串部分,新字符串即爲無重複字符的字符串
            res[:] = res[res.index(x) + 1:]
            # 擴展窗口
            res.append(x)
        # 更新最大長度
        max_length = max(len(res), max_length)
    return max_length
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章