- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
- 3. Longest Substring Without Rep
这道题和《剑指offer》的第48题是一样的,属于动态规划问题。
本题要用到首尾两个指针,让它们分别指向不含重复字符的子字符串的头部和尾部。
只需遍历整个字符串一次,时间复杂度 。但这是以额外的空间复杂度为代价的。需要用一个字典保存尾指针已经扫过的字符,然后拿当前字符和字典中的字符进行比较。
如果当前字符在字典中已经出现过,那就表明重复了,此时要让头指针指向当前字符后面的一个字符。尾指针不断后移,直至遍历完整个字符串。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
res = lo = 0
temp = {}
for hi, cur in enumerate(s): # 让end直接出现在循环体中
if cur in temp:
lo = max(lo, temp[cur]+1)
temp[cur] = hi # 哈希表中的字符若有重复的索引,则总是会将其更新为最大的索引值
res = max(res, hi-lo+1)
return res
网友评论