leetcode force buckle brush Series title python - 3, no repeated characters of the longest substring

topic:

 

Given a string, you find out which does not contain a sub-length of the longest string of repeated characters.

 

Example 1:

 

Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring of characters without repetition is "abc", so its length is 3.

 

Example 2:

Input: "bbbbb" 
Output: 1 
Explanation: Because the longest substring is repeated characters without "b", so that its length is 1. 


solution:

Hash table method using: l, and is set around the double pointer r, traverse the string;
position of the hash table stored in a character s [i] is the latest in a string in the index + 1, key, value corresponding to s [i], I;
left pointer during traversal:
if s [i] is not in the HashMap is skipped;
otherwise, the pointer is set to l and l dic [s [r]] of the maximum value, i.e., after modification to ensure that the new string There are no repeated characters.
The maximum length of each update res

 1 class Solution:
 2     def lengthOfLongestSubstring(self, s: str) -> int:
 3         dic = {}
 4         l, res = 0, 0
 5         for r in range(len(s)):
 6             if s[r] in dic:
 7                 l = max(dic[s[r]], l)
 8             dic[s[r]] = r + 1
 9             res = max(res, r - l + 1)
10         return res

 



 

Guess you like

Origin www.cnblogs.com/zhangxingcomeon/p/11140063.html