3. Longest Substring Without Repeating Characters
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.
解题要点:
用一个dictionary来记录每个字符的index,然后有左右两个指针指向最大长度的字符串。在遍历字符时,如有重复的,把左指针更新为之前dict里字符index的后一位,最后计算长度,记录最长。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
mydict = {}
j = 0
maxNum = 0
for i in range(len(s)):
if s[i] in mydict:
j = max(j, mydict[s[i]] + 1)
mydict[s[i]] = i
maxNum = max(maxNum, i-j+1)
return maxNum
Last updated
Was this helpful?