本文共 942 字,大约阅读时间需要 3 分钟。
为了解决寻找最长子串而没有重复字符的问题,我们可以使用滑动窗口方法。这种方法在O(n)的时间复杂度和O(1)的空间复杂度下,能够高效地解决问题。
left和right,分别表示窗口的左端和右端。此外,current_start记录窗口的起始位置,max_len记录最长子串的长度。class Solution: def lengthOfLongestSubstring(self, s): left = 0 max_len = 0 current_start = 0 for right in range(len(s)): if s[right] in s[current_start:right]: current_start = right + 1 current_window = right - current_start + 1 if current_window > max_len: max_len = current_window return max_len
left和max_len初始化为0,current_start也初始化为0。right指针遍历字符串中的每个字符。current_start到当前字符的位置+1。max_len比较,更新最长长度。这种方法确保了在每次遍历时,窗口内的字符都是唯一的,并且能够在O(n)时间复杂度内找到最长子串。
转载地址:http://saqfk.baihongyu.com/