BiruLyu
5/22/2017 - 11:20 PM

3. Longest Substring Without Repeating Characters.java


class Solution(object):
    def lengthOfLongestSubstring(self, s): 
        """
        :type s: str
        :rtype: int
        """
        """
        At first, I used dynamic programming, the answer is right but time limit exceeded
        This solution use hash table and two pointer Approach, the time complexity is O(n)
        """
        
        if not s:
            return 0;
            
        maxlength = 0;
        usedChar = {};
        start = 0;
        
        for i in range(len(s)):
            
            if s[i] in usedChar and start <= usedChar[s[i]]:
                start = usedChar[s[i]] + 1;
            else:
                maxlength = max(maxlength, i - start + 1);
            
            usedChar[s[i]] = i;
            
        return maxlength;
                
                
                    
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start = 0;
        int end = 0;
        HashMap<Character, Integer> dict = new HashMap<Character, Integer>();
        int res = 0;
        while(end < s.length()){
        	char c = s.charAt(end);
        	if( dict.containsKey(c) && start <= dict.get(c)){
        		start = dict.get(c) + 1;
        	} else {
        		res = Math.max(res, end - start + 1);
        	}
        	dict.put(s.charAt(end), end);
        	end++;
        }
        return res;
    }
}