首页 > 其他 > 详细

[LeetCode]3 Longest Substring Without Repeating Characters

时间:2015-01-02 16:14:59      阅读:248      评论:0      收藏:0      [点我收藏+]

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

原文:http://7371901.blog.51cto.com/7361901/1598391

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!