当前位置:网站首页>Longest string without duplicate characters (leetcode 3)

Longest string without duplicate characters (leetcode 3)

2022-06-12 11:56:00 Liyihe beats Xiao Tai

Author URI : Li Yihe beat Xiao Tai's blog
* Personal introduction : Hello everyone , I'm Li Yihe !( ̄▽ ̄)~*
Remember the praise. 、 Collection 、 Comment on ️️️
Study carefully !!!

Given a string s , Please find out that there are no duplicate characters in it Longest substrings The length of .
 Insert picture description here

 

Solution 1 : The sliding window

   Because to find the longest string that is not repeated , We need two pointers , The left pointer is fixed first , The pointers on the right are added to the set one by one , Determine whether there is a duplicate value each time , If so, it's over , Judge whether the length of this time is longer than that of the last time , Then the left pointer moves one... To the right , Then the right pointer continues the above operation until the end .

public int lengthOfLongestSubstring(String s) {
    
        Set<Character> set=new HashSet<Character>();
        int length=s.length();
        int rigth=0,max=0;
        for(int i=0;i<length;i++){
    
            if(i!=0)
                set.remove(s.charAt(i-1));
            while(rigth<length&&!set.contains(s.charAt(rigth))){
    
                set.add(s.charAt(rigth));
                rigth++;
            }
            max=Math.max(max,rigth-i);
        }
        return max;
    }

原网站

版权声明
本文为[Liyihe beats Xiao Tai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121155116019.html