Leetcode:3. 无重复字符的最长子串

//这道题我花了一晚上才把它调试通,心疼自己的智商一秒,关键部分在于Start的更新时我忽略了一种情况,导致很多次不能提交WTF大哭大哭大哭

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n=s.length(),ans=0;
        int i,start;
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        for(i=0,start=0;i<n;i++) {
        	if(map.containsKey(s.charAt(i))) {
        		start=Math.max(map.get(s.charAt(i))+1, start);/*T比如出现p....其他字符...p的情况,如果只考虑第一种,那么你在最后计算ans时i-start变得很大。从而错误
        	}
            ans=Math.max(ans,i-start+1);//这两行首先要确定,然后根据后面对应的I值确定if 中Start的更新。
            map.put(s.charAt(i),i);
        }
        	
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/God_Mood/article/details/80658786