無重複字符的最長子串

給定一個字符串,找出不含有重複字符的最長子串的長度。

示例:

給定 "abcabcbb" ,沒有重複字符的最長子串是 "abc" ,那麼長度就是3。

給定 "bbbbb" ,最長的子串就是 "b" ,長度是1。

給定 "pwwkew" ,最長子串是 "wke" ,長度是3。請注意答案必須是一個子串"pwke" 是 子序列  而不是子串。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> pos = new HashMap<>();
        char[] ss = s.toCharArray();

        int max = 0, temp = 0;

        for(int i = 0; i < s.length(); i++){

            if( !pos.containsKey(ss[i]) ){
                pos.put(ss[i],i);
                temp++;
            }else{
                if(pos.get(ss[i]) + temp < i){
                    temp++;                
                }else{
                    max = Math.max(max,temp);
                    temp = i - pos.get(ss[i]);
                }
                pos.put(ss[i],i);
            }

        }
        max = Math.max(max,temp);
        return max;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章