LeetCode 149 Longest Substring Without Repeating Characters


Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb"is "abc", which the length is 3. For "bbbbb"the longest substring is "b", with the length of 1.
分析:非重複を見て、Hashを考えるべきだ.
この問題はHashMapで文字と対応する下付き文字の関係を保存することができて、それから遍歴して、もし繰り返しに出会ったら、直接前の繰り返し文字の出現位置を見つけることができて、前のすべてを0にクリアします.
どうやって前のすべてをクリアしますか?
ここではstart変数を用いて現在の文字列の開始位置を記録し,重複するものに遭遇するとstartからHashMapから既存値を除去し,重複する文字まで前の要素のクリアを実現する.
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        int start = 0;
        for(int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if(map.containsKey(c)){
                max = Math.max(max, map.size());
                for(int j=start; j<i; j++){
                    if(s.charAt(j) == c){
                        start = j+1;
                        break;
                    }
                    map.remove(s.charAt(j));
                }
            }else{
                map.put(c, i);
            }
        }
        return Math.max(max, map.size());
    }
}

以下の解法は,バケツ配列思想を用い,すべてASCII文字であると仮定し,長さ256の配列を辞書とし,原理はHashと同様であり,制限は文字がASCIIであると仮定する.
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        boolean[] flag = new boolean[256];
        
        int result=0;
        int j=0;
        char[] arr = s.toCharArray();
        
        for(int i=0; i<arr.length; i++){
            char c = arr[i];
            if(flag[c]){//    ,      
                result = Math.max(result, i-j);
                for(int k=j; k<i; k++){
                    if(arr[k]==c){//  c   ,  j
                        j=k+1;
                        break;
                    }
                    flag[arr[k]]=false;
                }
            }else
                flag[c]=true;
        }
        result = Math.max(arr.length-j,result);
        return result;
    }
}