题目描述
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: 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.
代码实现
# 两种方法的left和right存的都是不重复最长字串
class Solution(object):
def lengthOfLongestSubstring(self, s):
# 方法一,wordidx存的是当前时刻出现的所有词的最新index,这个index可能是在left前(例:pwwped的第2个p)
"""
:type s: str
:rtype: int
"""
res=0
left,right = 0,0
wordidx = dict()
for right in range(len(s)):
if s[right] in wordidx:
left = max(left, wordidx[s[right]]+1)
wordidx[s[right]]=right
res = max(res, right-left+1)
return res
def lengthOfLongestSubstring(self, s):
# 方法二,set与left和right间字串对应,存的是当前位置的最长字串的字符,与方法一在确定left边界时有区别
"""
:type s: str
:rtype: int
"""
res=0
left,right = 0,0
words = set()
for right in range(len(s)):
while s[right] in words:
words.remove(s[left])
left+=1
words.add(s[right])
res = max(res,len(words))
return res