LeetCode-Longest Substring Without Repeating Characters

This question belong to the same category as those such as "longest substring without repeating characters", "minimum window substring", and "substring with concatenation of all words". To solve this kind of question we can use two pointers and a hash table. When the key of the hash table is char, we can simply use an array as the hash table. The most important idea in solving this kind of questions is "how to update the "start" pointer" and the solution to these questions seem usually differ only in this respect.

这段话写的很好, 都是用hash 有的题用map(longest substring at most 2 distinct char)有的题用hashset就可以(这个题)然后记录一个start指针

检查新碰到的这个char之前遇到过没有,假如遇到过就将start移动到这个char第一次出现过的地方的后面 就是重新开始一个substring。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if ( s == null || s.length() == 0 )
            return 0;
        HashSet<Character>set = new HashSet<Character>();
        int len = 0;
        int start = 0;
        int longest = 0;
        for ( int i = 0; i < s.length(); i ++ ){
            if ( !set.contains(s.charAt(i))) {
                set.add(s.charAt(i));
                len ++;
            }
            else{
                while ( s.charAt(start) != s.charAt(i)){
                    set.remove(s.charAt(start));
                    start ++;
                }
                start ++;
                len = i - start +1;
            }
            if ( len > longest)
                longest = len;
        }
        return longest;
    }
}

下面这个人写的更简洁一点 用了hashmap value存这个char出现过的所有位置 省去了我一个一个移动start的这步,直接移动到max(这个key随影的values)就是上一次出现的地方

   public int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }
才意识到 这就是dp了 晕



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