美文网首页算法
2018-01-28 longest substring

2018-01-28 longest substring

作者: BlackChen | 来源:发表于2018-01-28 15:43 被阅读8次

    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;
        }
    

    相关文章

      网友评论

        本文标题:2018-01-28 longest substring

        本文链接:https://www.haomeiwen.com/subject/dqfzaxtx.html