LeetCode 3无重复最长子串:滑动窗口实现超时问题解析
关于LeetCode无重复字符最长子串滑动窗口实现的疑问
我在解决LeetCode的《无重复字符的最长子串》题目,题目要求:给定字符串s,找出其中无重复字符的最长子串的长度。约束条件为:0 ≤ s.length ≤ 5*10^4,s包含英文字母、数字、符号和空格。
我使用滑动窗口算法实现的代码如下:
def lengthOfLongestSubstring(str): # define base case if (len(str) < 2): return len(str) # define pointers and frequency counter left = 0 right = 0 freqCounter = {} # used to store the character count maxLen = 0 while (right < len(str)): # adds the character count into the frequency counter dictionary if (str[right] not in freqCounter): freqCounter[str[right]] = 1 else: freqCounter[str[right]] += 1 # print (freqCounter) # runs the while loop if we have a key-value with value greater than 1. # this means that there are repeated characters in the substring. # we want to move the left pointer by 1 until that value decreases to 1 again. E.g., {'a':2,'b':1,'c':1} to {'a':1,'b':1,'c':1} while (len(freqCounter) != right-left+1): # while (freqCounter[str[right]] > 1): ## Time Limit Exceeded Error print(len(freqCounter), freqCounter) freqCounter[str[left]] -= 1 # remove the key-value if value is 0 if (freqCounter[str[left]] == 0): del freqCounter[str[left]] left += 1 maxLen = max(maxLen, right-left+1) # print(freqCounter, maxLen) right += 1 return maxLen print(lengthOfLongestSubstring("abcabcbb")) # 3 'abc'
我遇到了一个困惑:当使用while (freqCounter[str[right]] > 1):作为内层循环的判断条件时,提交代码会出现Time Limit Exceeded超时错误;但换成while (len(freqCounter) != right-left+1):就能正常通过测试。我原以为前者是O(1)的字典元素访问操作,效率应该更高,却没想到反而慢很多。同时我也想知道,当前的滑动窗口实现是否还有优化的空间。
内容的提问来源于stack exchange,提问作者Jessica
相关产品推荐
相关产品推荐

