Programmer Upgrade Daguai Level 3: Using the sliding window, how to find the longest substring?

Hi everyone, I am "@不飞的小飞驴"

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

Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: Because the longest substring without repeated characters is "abc", its length is 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: Because the longest substring without repeated characters is "b", its length is 1.
Example 3:
Input: s = "paakea"
Output: 3
Explanation: Because the longest substring without repeated characters is "ake", its length is 3.
Please note that your answer must be the length of the substring, "pake" is a subsequence, not a substring.

First of all, what solutions do you think of, please comment below.

Overall idea: The main idea used in this question is: sliding window

What is a sliding window?

For example, a queue, such as abcabcbb in the example, enters this queue (window) for abc to meet the requirements of the problem, when it enters a again, the queue becomes abca, which does not meet the requirements at this time. So, we have to move this queue!
How to move it?
We only need to move the elements on the left side of the queue until the problem requirements are met!
Always maintain this queue, find the longest length of the queue, and find the solution!

program:

public class Solution{
    
    
public int lengthOfLongestSubstring(String s){
    
    
	int n=s.length();
	set<Character> set =new HashSet<>();
	int ans=0,i=0,j=0;
	while(i<n&&j<n){
    
    
		if(!set.contians(s.CharAt(j))){
    
    
			set.add(s.charAt(j++));
			ans=Math.max(ans,j-i);
		}else{
    
    
			set.remove(s.charAt(i++));
		}
	} 
	return ans;
	}
}

Guess you like

Origin blog.csdn.net/u014251610/article/details/113664895