当前位置:网站首页>Daily question - longest substring without repeated characters

Daily question - longest substring without repeated characters

2022-07-05 05:28:00 ThE wAlkIng D

Title Description

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

Problem analysis ( This question uses a sliding window +HashMap)

  1. So let's set up a map aggregate ( Record the storage location of different strings ) And a temporary variable to store the longest character length
  2. Use double pointer end, start; Traversal string , First turn on the end Take out the characters of the pointer
  3. If map Set has the same characters , Change the starting position
  4. Otherwise, update Res Value , stay map Sets store different characters and their positions .

Code instance

class Solution {
    
    public int lengthOfLongestSubstring(String s) {
    
        int n = s.length();
        int res = 0;
        Map<Character,Integer> map = new HashMap<>();
        for(int end = 0, start = 0; end < n; end++){
    
            char c = s.charAt(end);
            if(map.containsKey(c)){
    
                start = Math.max(map.get(c),start);
            }
            res = Math.max(res,end - start + 1);
            map.put(s.charAt(end),end + 1);// Why? end+1 You have to be careful ,start Guarantee start The starting position should be the next digit of the repeated string .
        }
        return res;

    }
}
原网站

版权声明
本文为[ThE wAlkIng D]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050525449790.html