Wednesday, January 7, 2015

LeetCode 3: 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.
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        // For example, for "abcefcghk", the first substing is "abcef", the second substring is "efcghk".
        int n = s.length();
        
        if (n == 0)
            return 0;
        
        // Save character and its sting index    
        Map<Character, Integer> map = new HashMap<>();
        
        int maxLen = 0;
        int start = 0; // Starting position of substring
        int end; // Position of previous duplicate
        
        for (int i = 0; i < n; i++)
        {
            if (!map.isEmpty())
            {
                if (map.containsKey(s.charAt(i)))
                {
                    if (maxLen < map.size())
                        maxLen = map.size();
                        
                    end = map.get(s.charAt(i));
                    
                    // Delete the characters before the previous duplicate (including the duplicate)
                    for (int j = start; j<= end; j++)
                         map.remove(s.charAt(j));
                    
                    // Update start posit      
                    start = end+1;
                }
            }
            
            map.put(s.charAt(i), i);
        }
        
        // Don't miss the last substring
        if (maxLen < map.size())
            maxLen = map.size();
            
        return maxLen;
    }
}

No comments:

Post a Comment