题目描述:
方法一:
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: slow = 0 fast = 0 res_max = 0 table = dict() while slow<len(s) and fast<len(s): if s[fast] in table: del(table[s[slow]]) slow+=1 else: table[s[fast]] = fast fast+=1 res_max = max(res_max,fast-slow) return res_max
优化:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int: # 定义变量存储子字符串 sub_str = "" # 存储最大长度 max_length = 0 # 遍历字符串 for i in range(len(s)): if s[i] in sub_str: # 如果第i个字符在子字符串中已经存在,删除包含重复字符及之前的所有字符 sub_str = sub_str.split(s[i])[1] # 追加第i个字符到子字符串中 sub_str += s[i] if len(sub_str) > max_length: max_length = len(sub_str) return max_length