LeetCode Day 4 (Find the longest string without repetition)

Get up early today! Come on, the rookie becomes a bird!

1. Topic:

Given a string s, please find the length of the longest substring that does not contain repeated characters.

Example 1:

Input: s = "abcabcbb"
Output: 3 
Explanation: Since the longest substring without repeating characters is "abc", its length is 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: Since the longest substring without repeating characters is "b", its length is 1.

hint:

  • 0 <= s.length <= 5 * 104
  • s Composed of English letters, numbers, symbols and spaces

2. Ideas:

Queue (sliding window method): Each time an element is entered into the queue, if the element is found to be an existing element in the queue, an element is repeatedly dequeued until the condition is met. Maintain such a queue all the time, find out the longest length of the queue, and then find the solution.

In python -> refers to the return value

It is necessary to record the data of the queue. There are several characters in it, and what are they.

At the same time, record what the maximum length is at the moment, and the longest substring.

Need to traverse.

3. Code:

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        n=len(s)
        l=[]
        max=0
        cur=0
        for i in range(n):
            if s[i] not in l:
                l.append(s[i])
                cur+=1
            else:
                while s[i] in l:
                    l.pop(0)
                    cur-=1
                l.append(s[i])
                cur+=1
            if (cur>max):
                max=cur
        return max

 

Guess you like

Origin blog.csdn.net/m0_51786204/article/details/129819135