題目來自https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without
repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
我的解答:
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
start, curlen, findlen = 0,0, 0
Seen = dict()
lenstr = len(s)
for i in range(lenstr):
ch = s[i]
if ch not in Seen or Seen[ch] < start:
curlen += 1
else:
if curlen > findlen:
findlen = curlen
start = Seen[ch] + 1
curlen = i - Seen[ch]
Seen[ch] = i
#if found at end
if curlen > findlen:
findlen = curlen
return findlen
說明:
這一題的難度標註爲“Medium", 算是中規中矩吧。
我的思路是構造字典,記錄出現過的字符的位置。從頭開始掃描,統計無重複字符串的長度。
當前字符ch沒有重複出現,則更新當前子串的無重複長度。start 指的是新串起始位置。
if ch not in Seen or Seen[ch] < start:
curlen += 1
重複出現,則檢查是否是當前最大解,是則更新。記錄新串起始位置和新串長度(利用Seen[ch] else:
if curlen > findlen:
findlen = curlen
start = Seen[ch] + 1
curlen = i - Seen[ch]
Seen[ch] = i
程序很簡單,重點是利用Seen[ch]來生成每次重新開始新串的起始位置和既有長度。
Python 的字典又一次發揮了作用。