首页 > 代码库 > [LeetCode]3 Longest Substring Without Repeating Characters

[LeetCode]3 Longest Substring Without Repeating Characters

https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/

http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html


public class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        if (s == null || s.isEmpty())
            return 0; // invalid input
            
        // A map of [char, position]
        Map<Character, Integer> map = new HashMap<>();
        
        char[] chars = s.toCharArray();
        int len = chars.length;
        
        int start = 0;
        int end = 0;
        int maxLen = -1;
        for (; end < len ; end ++)
        {
            char c = chars[end];
            Integer lastPos = map.get(c);
            if (lastPos == null)
            {
                map.put(c, end);
                int curLen = end - start + 1;
                if (curLen > maxLen)
                    maxLen = curLen;
            }
            else
            {
                // Clear all chars <= lastPos, including c.
                // Then update c with end.
                // reset start = lastPos + 1;
                for (int i = start ; i <= lastPos ; i ++)
                {
                    map.remove(chars[i]);
                }
                start = lastPos + 1;
                map.put(c, end);
            }
        }
            
        if (maxLen == -1) // All chars are the same. return 1.
            return 1;
        
        return maxLen;
    }
}


[LeetCode]3 Longest Substring Without Repeating Characters