[LeetCode]3. Longest Substring Without Repeating Characters (Medium) Python-2022.10.22
Posted on 2022-10-22 19:54 Uriel 閱讀(49) 評論(0) 編輯 收藏 引用 所屬分類: 閑來無事重切Leet Code 、游標.移動窗口最長無重復(fù)字符子串長度
維護兩個指針pos_l和pos_r,每次pos_r右移一位,如果該字符在pos_l~pos_r-1之間已經(jīng)出現(xiàn)過,則更新該字符最后出現(xiàn)的位置,同時pos_l右移一位,否則,更新最長無重復(fù)字符子串長度
一開始沒想清楚pos_l的更新,WA*4
維護兩個指針pos_l和pos_r,每次pos_r右移一位,如果該字符在pos_l~pos_r-1之間已經(jīng)出現(xiàn)過,則更新該字符最后出現(xiàn)的位置,同時pos_l右移一位,否則,更新最長無重復(fù)字符子串長度
一開始沒想清楚pos_l的更新,WA*4
1 #3
2 #Runtime: 108 ms
3 #Memory Usage: 13.5 MB
4
5 class Solution(object):
6 def lengthOfLongestSubstring(self, s):
7 """
8 :type s: str
9 :rtype: int
10 """
11 dict_s = {}
12 pos_l = 0
13 pos_r = 0
14 ans = 0
15 while pos_r < len(s):
16 if s[pos_r] in dict_s:
17 if dict_s[s[pos_r]] >= pos_l:
18 pos_l = dict_s[s[pos_r]] + 1
19 dict_s[s[pos_r]] = pos_r
20 else:
21 dict_s[s[pos_r]] = pos_r
22 ans = max(ans, pos_r - pos_l + 1)
23 pos_r += 1
24 return ans
2 #Runtime: 108 ms
3 #Memory Usage: 13.5 MB
4
5 class Solution(object):
6 def lengthOfLongestSubstring(self, s):
7 """
8 :type s: str
9 :rtype: int
10 """
11 dict_s = {}
12 pos_l = 0
13 pos_r = 0
14 ans = 0
15 while pos_r < len(s):
16 if s[pos_r] in dict_s:
17 if dict_s[s[pos_r]] >= pos_l:
18 pos_l = dict_s[s[pos_r]] + 1
19 dict_s[s[pos_r]] = pos_r
20 else:
21 dict_s[s[pos_r]] = pos_r
22 ans = max(ans, pos_r - pos_l + 1)
23 pos_r += 1
24 return ans