LeetCode Longest Substring Without Repeating Characters

原题链接在这里:https://leetcode.com/problems/longest-substring-without-repeating-characters/

String 题目,基本思路就是维护一个窗口[walker,runner]. walker,runner都是向右移,同时维护一个HashSet hs,用来存储这一段中的所有不同character。首先右侧窗口runner在前跑,每当遇到hs中没有的character,加入hs,知道遇到相同元素,说明以不符合要求,runner停下,准备移动左侧窗口walker。

移动左侧窗口walker前,先更新最大长度max(res, runner - walker)。然后开始移动walker,一直找到与此时runner指向的相同元素,之前的元素都需从hs中删除。

本应删掉此时walker指向的元素,但由于runner还要再次添加这个元素,并且那一行在else statement 里不方便改写,所以没有删掉walker此时指向的元素。

Note:无论hs中是否含有runner指向的元素,runner都要向后移,否则下一循环时就会错误减掉元素。

Time Complexity: O(n). runner只跑一遍string, n是string长度. Space Complexity: O(n). 用了HashSet.

AC Java:

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if(s == null || s.length() == 0){
 4             return 0;
 5         }
 6         int res = 0;
 7         HashSet<Character> hs = new HashSet<Character>();
 8         
 9         int walker = 0;
10         int runner = 0;
11         while(runner < s.length()){
12             if(!hs.contains(s.charAt(runner))){
13                 hs.add(s.charAt(runner));
14                 runner++;
15             }else{
16                 res = Math.max(res, runner-walker);
17                 while(s.charAt(walker) != s.charAt(runner)){
18                     hs.remove(s.charAt(walker));
19                     walker++;
20                 }
21                 walker++;
22                 runner++;
23             }
24         }
25         return Math.max(res, runner-walker);
26     }
27 }

 跟上一道Longest Substring with At Most Two Distinct Characters

你可能感兴趣的:(LeetCode Longest Substring Without Repeating Characters)