[leedcode 03] 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.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        //利用hashMap只需循环一次即可。
         //使用start和i两个指针维护子串,用Hash表记录字串中出现的字符。每次循环i右移1位,然后判断i右移之后所指向的字符是否在Hash表中出现            过:如果出现过,则表示出现重复字符,记录该子串长度,并与最长长度比较,然后,删除子串中重复字母之前的字符,并更新start;如果没出现过,         则说明没有重复字符,将该字符放入Hash表。
         /*
         时间复杂度O(n);
         空间复杂度O(m),m取决于非重复子串的长度*/
        HashMap<Character,Integer> map=new HashMap<Character,Integer>();
        int len=0;
        int res=0;
    
        int start=0;
        int i=0;
        for(i=0;i<s.length();i++){
            if(!map.containsKey(s.charAt(i))){
                map.put(s.charAt(i),i);
               /*  len=i-start+1;
                 res=Math.max(len,res);*/
            }else{
                 len=i-start;
                 res=Math.max(len,res);
                int t=map.get(s.charAt(i));
                for(int j=start;j<=t;j++){
                    map.remove(s.charAt(j));
                }
                start=t+1;
                map.put(s.charAt(i),i);
            }
        }
        return Math.max(res,i-start);
       // return res;
    }
}

 

posted @ 2015-07-04 14:03  ~每天进步一点点~  阅读(121)  评论(0编辑  收藏  举报