[LeetCode] 9.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.

想清楚了其实不难。用到HashMap,以字符为键,字符所在字符串的位置为值,i指针指向需求字符串的第一个字符,j指针遍历字符串,如果map没有该字符,就把键值对插入。如果有,则判断该键对应的值是否大于等于i,如果大于等于i则表示遇到重复的字符里,要更新max值(max为所求的最大无重复字符字符串的长度)。若小于i,表示之前有出现过该字符,但是不在起始字符之后,不用更新max值,直接更新键值对应的值即可。

 刚开始提交代码,一直是WA,Excepted A 是12,我的outcome是13。对比了网上的代码,思路一样,找不到错误。后来发现是

map.get(c)>=i 写成了
map.get(c)>i 想法对的,对应到代码就出错了。
import java.util.HashMap;
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int i=0,j=0;
        int max=0;
        HashMap<Character,Integer> map=new HashMap<Character,Integer>(); 
        char c='';
        while(j<s.length()){
            c=s.charAt(j);
            if(map.containsKey(c)&& map.get(c)>=i){  
                if((j-i)>max)
                    max=j-i;
                i=map.get(c)+1;
            }
            map.put(c,j);
            j++;
        }
        if((j-i)>max)
            max=j-i;
        return max;
        
    }
}

  

原文地址:https://www.cnblogs.com/guozhiguoli/p/3355145.html