算法

2018-01-28 longest substring

2018-01-28  本文已影响8人  BlackChen

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

public int lengthOfLongestSubstring(String s) {

        int start = 0;
        int max =0;
        int len = s.length();
        char[] test = s.toCharArray();
//边找,边put ,同时移动start指针
        HashMap<Character,Integer> map = new HashMap<Character, Integer>();
        for(int i = 0;i <len;i++){
            if(map.containsKey(test[i]) && map.get(test[i]) >= start)
            {
                int maxTmp = i - start;
                if(maxTmp > max){
                    max = maxTmp;
                }
                start = map.get(test[i])+1;
                map.put(test[i],i);
            }
            else{
                map.put(test[i],i);
            }
        }
        if(len - start > max){
            return len - start;
        }
        else{
            return max;
        }
    }

别人的做法

 public int lengthOfLongestSubstring2(String s) {
        int res = 0, left = 0, right = 0;
        HashSet<Character> t = new HashSet<Character>();
        while (right < s.length()) {
            if (!t.contains(s.charAt(right))) {
                t.add(s.charAt(right++));
                res = Math.max(res, t.size());
            } else {
                t.remove(s.charAt(left++));
            }
        }
        return res;
    }
上一篇 下一篇

猜你喜欢

热点阅读