[Leetcode]Longest Substring Without Repeating Characters

来源:互联网 发布:银行叫号机 淘宝 编辑:程序博客网 时间:2024/06/04 23:36

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

求没有重复字符的最长字符串~维护两个指针start, end;保证两个指针间没有重复元素,用hashmap判断是否有重复元素,如果end指针遇到了重复元素,把start指针往后移到第一个和end指针相同的字符之后(注意移动时要记得把start指针原来所在的位置及移动后的位置之间的元素从dictionary中删除掉)~代码如下,时间复杂度为O(n)

class Solution:    # @return an integer    def lengthOfLongestSubstring(self, s):        if s is None or len(s) == 0: return 0        res = 0; dict = {}        start, end = 0, 0        while end < len(s):            if s[end] in dict:                tmp = dict[s[end]]                for i in xrange(start, dict[s[end]] + 1):                    del dict[s[i]]                start = tmp + 1            else:                res = max(res, end - start + 1)                dict[s[end]] = end                end += 1        return res

代码还可以再简洁一点~下面的代码就省去了从dict中删除前面重复元素之前的元素的步骤,所以效率也就更高~~Runtime 也从150ms左右降低到90ms~

class Solution:    # @return an integer    def lengthOfLongestSubstring(self, s):        if s is None or len(s) == 0: return 0        dict = {}; start = 0; maxLen = 0        for end in xrange(len(s)):            if s[end] in dict and dict[s[end]] >= start:                start = dict[s[end]] + 1            dict[s[end]] = end            maxLen = max(maxLen, end - start + 1)        return maxLen


0 0