3. Longest Substring Without Repeating Characters
Description:
Given a string, find the length of the longest substring without repeating characters.
给定字符串,求出最长的不重复的子串。
Example:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
Solution:
class Solution:
def lengthOfLongestSubstring(self, s):
start = maxLength = 0
usedChar = {}
for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]: # “并且”
start = usedChar[s[i]] + 1
else:
maxLength = max(maxLength, i - start + 1) # max的使用很巧妙
usedChar[s[i]] = i # 将值填入
return maxLength
需要3个临时变量来查找最长子串:开始,最大长度,并使用字符。从一系列的字符开始,一次一个。如果当前字符是在usedchars map中,这将意味着我们已经看过并存储了相应的索引。如果它在那里,开始索引是<=那个索引,更新开始到最后看到重复的索引+ 1。这将把开始索引放在合适的位置。通过当前值的最后一次看到的副本。这让我们拥有了不包含重复的最长可能子串。如果不是在usedchars地图,我们可以计算出到目前为止看到的最长的子串。只需使用当前索引减去开始索引即可。如果值比最大长度长,将最大长度设置为它。最后,更新usedchars地图包含我们已经完成的当前值。@tapatio
class Solution:
"""
:type s: str
:rtype: int
"""
def lengthOfLongestSubstring(self, s):
start = maxLength = 0
usedChar = {}
# 调用enumerate, 思想类似
for index,char in enumerate(s):
if char in usedChar and start <= usedChar[char]:
start = usedChar[char] + 1
else:
maxLength = max(maxLength, index - start + 1)
usedChar[char] = index
return maxLength