LeetCode 3
https://leetcode.cn/problems/longest-substring-without-repeating-characters/
双指针解法
def longest_substring_without_repeating_characters(s: str) -> int:
"""
求解无重复字符的最长子串
:param s: 给定字符串
:return: 无重复字符的最长子串长度
"""
# 创建字典来存储字符出现的位置
char_index = {}
max_len = 0
start = 0
# 遍历字符串
for i, char in enumerate(s):
# 如果该字符已经出现过
if char in char_index and char_index[char] >= start:
# 更新最长子串长度
max_len = max(max_len, i - start)
# 更新子串的起始位置
start = char_index[char] + 1
# 更新字符出现的位置
char_index[char] = i
# 更新最长子串长度
max_len = max(max_len, len(s) - start)
return max_len
print(longest_substring_without_repeating_characters("abcabcbb"))
这段代码求解了无重复字符的最长子串。主要思路是使用双指针来遍历字符串,并使用字典来记录每个字符出现的位置。
在遍历字符串时,如果当前字符已经在字典中出现过,并且出现的位置在当前子串的范围内,就更新当前子串的起始位置,并更新最长子串长度。如果当前字符没有出现过,或者出现的位置不在当前子串的范围内,就将当前字符的位置添加到字典中。
最后,在遍历完整个字符串后,需要再次更新最长子串长度,因为最长子串可能在最后一段。
这种做法,时间复杂度是 O(n),空间复杂度是O(min(n, m)),n为字符串长度,m为字符集大小。
代码中使用了python自带的字典类型,可以很方便地实现对字符出现位置的记录,并且查找操作的时间复杂度是 O(1),这也是这种做法能够在O(n)的时间内完成的原因。





