[LeetCode3] 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.

从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。比如


直到扫描到最后一个字母。
C++实现

<span style="font-family:Helvetica Neue, Helvetica, Arial, sans-serif;color:#333333;">int lengthOfLongestSubstring(string s) {
        int maxL=0;
        int len =0;
        int counts[26];
        memset(counts, -1, 26*sizeof(int));
    
        for(int i=0; i<s.size(); i++,len++){
            if(counts[s[i]-'a']>=0){
            maxL = max(maxL, len);
            len = 0;
            i = counts[s[i]-'a']+1;
            memset(counts,-1,26*sizeof(int));
        }
        counts[s[i]-'a'] = i;
    }
    return max(len, maxL);
    }</span>


Java实现

<span style="font-family:Helvetica Neue, Helvetica, Arial, sans-serif;color:#333333;">public int lengthOfLongestSubstring(String s) {
        if(s.length() == 0) return 0;
		int start = 0;
		int end = 0;
		int maxLen = 0;
		HashMap<Character, Integer> charMap = new HashMap<Character,Integer>();
		while(end<s.length()){
			if(!charMap.containsKey(s.charAt(end))){
				charMap.put(s.charAt(end), end);
				int len = end-start+1;
				maxLen = Math.max(len, maxLen);
			}else{
				int val = charMap.get(s.charAt(end));
				for(int i=start;i<val+1;i++)
					charMap.remove(s.charAt(i));
				start = val+1;
				charMap.put(s.charAt(end), end);
			}
			end++;
		}
		return maxLen;
    }</span>

你可能感兴趣的:(LeetCode,String,HashMap)