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.
Example 3:
Input: "pwwkew" Output: 3 Explanation: Because the longest sub-string is repeated characters without "wke", so its length is 3. Please note that your answer must be a substring of length, "pwke" is a sub-sequence, not a substring.
Ideas:
The main idea is to use this question: sliding window
What is the sliding window?
Is actually a queue, such as in the example abcabcbb
, enter the queue (window) to abc
meet the subject requirements, when re-entering a
, into a queue abca
, this time does not meet the requirements. So, we want to move the queue!
How do you move?
We just put the elements left out of the queue on the line, until meeting questions asked!
Has maintained such a queue, the queue to find the longest length of time appears, find the solution!
Time complexity: O (n-) O ( n- )
Code:
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if not s:return 0 left = 0 lookup = set() n = len(s) max_len = 0 cur_len = 0 for i in range(n): cur_len += 1 while s[i] in lookup: lookup.remove(s[left]) left += 1 cur_len -= 1 max_len = max(cur_len, max_len) lookup.add(s[i]) return max_len