返回
妙解 leetcode3:寻觅无重复字符的最长子串 | 刷题打卡
前端
2024-02-06 21:40:37
前言
第一次参加掘金打卡活动,别的不说,主要是奔着奖励来的。4.12 开始为了达到 14 题小目标,冲冲冲!!!
这是第五题。
题目
题目链接:无重复字符的最长子串
给定一个字符串,请找出其中不含有重复字符的最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,答案必须是一个子串,"pwke" 是一个子序列,不是子串。
哈希表法
哈希表法是解决这个问题的一种常见方法。我们使用一个哈希表来存储每个字符及其最近出现的位置。
当我们遍历字符串时,我们检查哈希表中是否包含当前字符。如果包含,则我们更新该字符的最近出现位置。否则,我们将该字符及其当前位置插入哈希表中。
我们还维护一个变量来存储无重复字符的最长子串的长度。每次我们找到一个新的无重复字符的最长子串时,我们就更新这个变量。
def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
# Create a hash table to store the characters and their positions.
char_index_map = {}
# Initialize the length of the longest substring to 0.
max_length = 0
# Initialize the start and end indices of the current substring.
start = 0
end = 0
# Iterate over the string.
for i, char in enumerate(s):
# If the character is in the hash table and its position is greater than or equal to the start index of the current substring,
# then we need to update the start index of the current substring.
if char in char_index_map and char_index_map[char] >= start:
start = char_index_map[char] + 1
# Update the position of the character in the hash table.
char_index_map[char] = i
# Update the end index of the current substring.
end = i
# Update the length of the longest substring.
max_length = max(max_length, end - start + 1)
# Return the length of the longest substring.
return max_length
滑动窗口法
滑动窗口法是解决这个问题的另一种方法。我们使用一个滑动窗口来跟踪无重复字符的最长子串。
当我们遍历字符串时,我们将当前字符添加到滑动窗口中。如果当前字符已经存在于滑动窗口中,则我们将滑动窗口的起始位置移到该字符之后。
我们还维护一个变量来存储无重复字符的最长子串的长度。每次我们找到一个新的无重复字符的最长子串时,我们就更新这个变量。
def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
# Initialize the length of the longest substring to 0.
max_length = 0
# Initialize the start and end indices of the current substring.
start = 0
end = 0
# Create a set to store the characters in the current substring.
char_set = set()
# Iterate over the string.
for i, char in enumerate(s):
# If the character is in the set, then we need to update the start index of the current substring.
while char in char_set:
char_set.remove(s[start])
start += 1
# Add the character to the set.
char_set.add(char)
# Update the end index of the current substring.
end = i
# Update the length of the longest substring.
max_length = max(max_length, end - start + 1)
# Return the length of the longest substring.
return max_length
总结
在本文中,我们探讨了如何在给定字符串中找到无重复字符的最长子串。我们使用哈希表和滑动窗口技术来解决这个问题。