leetcode #2 Longest Substring Without Repeating Characters
筒子们要注意啊,输入”pwwkew”,最大不重复字符串是”wke”,而”pwke” 是最大子序列。 下面开始分析 1. 把初始长度和最大长度都设为1 2. 新建一个遍历过的字符字典 3. 如果s[i]在字典中且开始的位置小于等于当前遍历的位置 4. 开始位置等于当前位置加一 5. 否则,最大长度等于max(最大长度,i-start+1) 6. 把当前位置赋给usedChar[s[i]] 7. 循环完后返回最大长度 8. 时间复杂度为O(n)
下面贴代码
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
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)
usedChar[s[i]] = i
return maxLength