2018-01-28 longest substring

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 map = new HashMap();
        for(int i = 0;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 t = new HashSet();
        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;
    }

你可能感兴趣的:(2018-01-28 longest substring)