LeetCode3. Longest Substring Without Repeating Characters 子字符串长度

字符串的长度

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

暴力破解
滑动窗口(双指针法)
  1. 设置左指针left和右指针right
  2. 置Map表示左指针和右指针之间的字母
  3. 右指针先走,把没有遇到过重复的字母加入Map中。记录长度
  4. 如果遇到已经在Map中的字母,则左指针走一步。 并从map中删除
  5. 直到右指针走到头。
ublic 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) {
        // try to extend the range [i, j]
        if (!set.contains(s.charAt(j))){
            set.add(s.charAt(j++));
            ans = Math.max(ans, j - i);
        }
        else {
            set.remove(s.charAt(i++));
        }
    }
    return ans;
}	
滑动窗口改进

在滑动窗口中,左指针是一步一步走的。然而实际上并不需要一步一步走,可以直接到上一次该字母的位置。

public int lengthOfLongestSubstring(String s) {
    int length = s.length();
    int left = 0;
    int right = 0;
    int maxLength = 0;
    Map<Character,Integer> map = new HashMap<>();
    while(right < length){
        Character cur = s.charAt(right);
        if(map.containsKey(cur) && map.get(cur) > left){
            left = map.get(cur);
            map.put(cur,right + 1);
        } else {
            map.put(cur,right + 1);
            maxLength = Math.max(maxLength,right - left + 1);
        }
        right++;
    }
    
    return maxLength;
}
发布了36 篇原创文章 · 获赞 8 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_32763643/article/details/103965027