https://leetcode.com/problems/longest-substring-without-repeating-characters/html
Given a string, find the length of the longest substring without repeating characters.python
Example 1:算法
Input: "abcabcbb"
Output: 3 Explanation: The answer is , with the length of 3. "abc"
Example 2:app
Input: "bbbbb"
Output: 1 Explanation: The answer is , with the length of 1. "b"
Example 3:ide
Input: "pwwkew"
Output: 3 Explanation: The answer is , with the length of 3. Note that the answer must be a substring, is a subsequence and not a substring."wke""pwke"
1 class Solution: 2 def lengthOfLongestSubstring(self, s: str) -> int: 3 d = dict() # current index of character 4 left, right, maxlen = 0, 0, 0 5 n = len(s) 6 7 while right < n: 8 # if char in dict[j'],skip all the elements in the range [i,j'] and let i to be j'+1 directly. 9 if s[ right ] in d: 10 left = max( d[ s[ right ] ], left ) 11 12 maxlen = max( right - left + 1, maxlen ) 13 14 # set next available index for left, i.e. j'+1 15 d[ s[ right ] ] = right + 1 16 17 right += 1 18 19 return maxlen 20 21 def lengthOfLongestSubstring1(self, s: str) -> int: 22 dict = set() 23 24 n = len(s) 25 left, right, maxlen = 0, 0, 0 26 27 while right < n: 28 if s[ right ] not in dict: 29 dict.add( s[ right ] ) 30 maxlen = max( maxlen, right - left + 1 ) 31 right += 1 32 else: 33 dict.remove( s[ left ] ) 34 left += 1 35 36 return maxlen