Longest Substring Without Repeating Characters

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s==null) {
            return 0;
        }
        int max = 0; 

        //Use a hash table to track existing characters and their position
        HashMap<Character, Integer>map = new HashMap<Character, Integer>();
        int start = 0; 

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            //if a repeated char occurs, check from the previously repeated char
            if (map.containsKey(c)) {
                max = Math.max(max, map.size());
                while(map.containsKey(c)) {
                    map.remove(s.charAt(start));
                    start++;
                }
                map.put(c,i);
            } else {
                map.put(c,i);
            }
        }
        max = Math.max(max, map.size());
        return max;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s