今天的题目是3. 无重复字符的最长子串
用双指针滑动窗口的方式,时间复杂度O(n)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
# 如果字符串s为空,返回0
if not s:return 0
# 保存窗口内字符串
lookup = list()
n = len(s)
# 最大子串长度
max_len = 0
# 当前窗口长度
cur_len = 0
# 遍历字符串s
for i in range(n):
val = s[i]
# 如果该值不在窗口中
if not val in lookup:
# 添加到窗口内
lookup.append(val)
# 当前长度+1
cur_len+=1
# 如果该值在窗口中已存在
else:
# 获取其在窗口中的位置
index = lookup.index(val)
# 移除该位置及之前的字符,相当于上图中的图3到图4
lookup = lookup[index+1:]
lookup.append(val)
# 当前长度更新为窗口长度
cur_len = len(lookup)
# 如果当前长度大于最大长度,更新最大长度值
if cur_len > max_len:max_len = cur_len
# 返回最大子串长度
return max_len
987/987 cases passed (76 ms)
Your runtime beats 59.26 % of python3 submissions
Your memory usage beats 5.01 % of python3 submissions (13.5 MB)
看还有动态规划,竟然如此之慢
987/987 cases passed (568 ms)
Your runtime beats 12.08 % of python3 submissions
Your memory usage beats 5.01 % of python3 submissions (13.6 MB)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if s == '':
return 0
if len(s) == 1:
return 1
def find_left(s, i):
tmp_str = s[i]
j = i - 1
while j >= 0 and s[j] not in tmp_str:
tmp_str += s[j]
j -= 1
return len(tmp_str)
length = 0
for i in range(0, len(s)):
length = max(length, find_left(s, i))
return length