leetcode 3. Longest Substring Without Repeating Characters 最长非重复子串的长度 滑动窗口法
生活随笔
收集整理的這篇文章主要介紹了
leetcode 3. Longest Substring Without Repeating Characters 最长非重复子串的长度 滑动窗口法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接
根據我們之前介紹的滑動窗口法的解法:
滑動窗口法詳解
leetcode 438. Find All Anagrams in a String 滑動窗口法
這題,我們不難解決,使用之前的模板。可得如下解法
from collections import defaultdictclass Solution:def lengthOfLongestSubstring(self, s):begin, end , counter, d = 0, 0, 0, 0map_dict = defaultdict(int)while end < len(s):c = s[end]map_dict[c] += 1# counter表示重復字符的個數if map_dict[c] > 1:counter += 1end += 1# 將begin一直移到第一個重復字符的位置while counter > 0:char_tmp = s[begin]if map_dict[char_tmp] > 1:counter -= 1map_dict[char_tmp] -= 1begin += 1# 每次計算下當前子串長度d = max(d, end - begin)return d
提供一種更短的解法:
class Solution:def lengthOfLongestSubstring(self, s):dic, res, start, = {}, 0, 0for i, ch in enumerate(s):if ch in dic:start = max(start, dic[ch]+1)res = max(res, i-start+1)dic[ch] = ireturn res
總結
以上是生活随笔為你收集整理的leetcode 3. Longest Substring Without Repeating Characters 最长非重复子串的长度 滑动窗口法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 438. Find A
- 下一篇: leetcode Longest Sub