3. 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.

When search for char in map, you need make sure no search pass the current starting index.

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

        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int lastDupIndex = -1;
        int maxSize = 0;
        char [] chars = s.toCharArray();
        for(int i=0;i<chars.length;i++) {
            Integer lastIndex = map.get(chars[i]);
            if (lastIndex != null && lastDupIndex < lastIndex) {
                lastDupIndex = lastIndex;
            }
            maxSize = Math.max(maxSize, i-lastDupIndex);
            map.put(chars[i], i);
        }

        return maxSize;
    } 
}

results matching ""

    No results matching ""