首页 > 其他 > 详细

3. Longest Substring Without Repeating Characters

时间:2017-07-25 23:55:55      阅读:398      评论:0      收藏:0      [点我收藏+]

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

 

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.

 

 
 

Sol:

 

Instead of using a set to tell if a character exists or not, we could define a mapping of the characters to its index. Then we can skip the characters immediately when we found a repeated character.

The reason is that if s[j] have a duplicate in the range [i, j) with index j‘, we don‘t need to increase iilittle by little. We can skip all the elements in the range [i, j‘] and let ii to be j‘ + 1 directly.

 

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        # Using HashMap
        # Time O(n)
        
        n = len(s)
        ans = 0
        # map stores the index of the current element 
        map = collections.defaultdict(int)
        
        # try to extend to the range[i, j]
        i = 0
        
        for j in range(n):
            
            if s[j]:
                i = max(i, map[s[j]])
            ans = max(ans, j - i + 1)
            map[s[j]] = j + 1
            
        return ans

 

3. Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/prmlab/p/7236904.html

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