lintcode-medium-Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

 

Example

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.

Challenge

O(n) time

 

值得注意的的一点是删除之前的条目时,应该先求出要删除的个数,然后再开始删除

如果不这样做,可能导致判断条件求得的截止index为null,从而导致异常

public class Solution {
    /**
     * @param s: a string
     * @return: an integer 
     */
    public int lengthOfLongestSubstring(String s) {
        // write your code here
        
        if(s == null || s.length() == 0)
            return 0;
        
        int slow = 0;
        int fast = 1;
        int result = 1;
        int len = s.length();
        
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        map.put(s.charAt(0), 0);
        
        while(fast < len){
            
            while(fast < len && !map.containsKey(s.charAt(fast))){
                map.put(s.charAt(fast), fast);
                fast++;
                
                result = Math.max(result, fast - slow);
            }
            
            if(fast < len){
                int temp = map.get(s.charAt(fast)) + 1;
                
                for(int i = slow; i <= temp - 1; i++)
                    map.remove(s.charAt(i));
                
                slow = temp;
                map.put(s.charAt(fast), fast);
                fast++;
            }
        }
        
        return result;
    }
}

 

posted @ 2016-03-29 17:20  哥布林工程师  阅读(146)  评论(0编辑  收藏  举报