两种解法:
1. 遍历字符串中每个位置符合需求的子串长度检测到重复字符时,跳转到上一子串中该重复字符位置的下一个作为当前子串起始位置。具体实现时,初始化一个布尔型的数组,每个位置对应字符的ASCII码值,记录是否在子串中出现。初始化i作为子串起始位置,j作为当前子串结束位置。由于i和j无重复赋值,时间复杂度,空间复杂度
。
2. 与解法1类似,不同之处是把数组改为一个字典,把遍历改为查表操作,节省遍历消耗的时间复杂度,节省一个循环,时间复杂度,空间复杂度
。
相较我的心路,优势在于,结束位置不会重复赋值,而是单向不回头。
Runtime: 44 ms, faster than 71.61% of Python online submissions forLongest Substring Without Repeating Characters.
Memory Usage: 12.9 MB, less than 7.82% of Python online submissions forLongest Substring Without Repeating Characters.
Python源码:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
char_map = {}
i = 0
max_len = 0
for j in range(len(s)):
if s[j] in char_map and char_map[s[j]] >= i:
i = char_map[s[j]] + 1
char_map[s[j]] = j
max_len = max(j - i + 1, max_len)
return max_len
我的心路:
方法偏brute force,从左至右遍历字符串,比较从每个字符开始的无重复子串长度。
一个小的改进是,为每个子串保存一个字典,键为子串中的字符,值为字符绝对位置,在检测字符串中下一个字符时,如果发现重复,则从原字符串中的重复字符的下一个开始继续遍历。时间复杂度,空间复杂度
,后者是因为字符类型有限,不会超过某一阈值。
Runtime: 532 ms, faster than 10.02% of Python online submissions forLongest Substring Without Repeating Characters.
Memory Usage: 12.2 MB, less than 42.19% of Python online submissions for Longest Substring Without Repeating Characters.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
longest = 0
i = 0
while i <= len(s) - 1:
sub = {}
j = i
i_tmp = i
while j <= len(s) - 1:
if s[j] in sub:
if j - i > longest:
longest = j - i
i_tmp = sub[s[j]] + 1
break
else:
sub[s[j]] = j
j += 1
if j == len(s):
if j - i > longest:
longest = j - i
break
i = i_tmp
return longest