最长不含重复字符的子字符串
题目
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
s . l e n g t h < = 40000 s.length <= 40000 s.length<=40000
思路1 滑动窗口+dp
leetcode题解
题目中要求答案是子串的长度,故子串一定连续,可以看成一个滑动窗口不断更新窗口的最大值,并维护窗口内不能有重复字符。
(1)初始化头尾指针指向第一个字符
(2)tail右移,同时判断tail指向的字符是否在滑动窗口内
- 不在,将该元素加入窗口,并更新窗口最大值
- 在,head右移知道窗口不包含该元素
(3)返回窗口长度历史中的最大值
思路2 哈希表优化滑动窗口
使用哈希表记录每个字符的下一个索引,然后尽量向右移动尾指针来拓展窗口,并更新窗口的最大长度。如果尾指针指向的元素在哈希表中,将头指针直接移动到重复元素的下一个位置。
(1)tail一直向右移动
(2)如果尾指针指向的元素在hash中:
- head直接跳跃到重复字符的下一位
(3)更新哈希表和窗口长度。
C++ 哈希优化
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char, int> hash;
int res = 0;
int head = 0, tail = 0;
while(tail<s.size())
{
if(hash.find(s[tail])!=hash.end())
head = max(head, hash[s[tail]]+1); //head跳到重复处的下一位
hash[s[tail]] = tail;
res = max(tail-head+1, res);
++tail;
}
return res;
}
};
python 哈希优化
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
head = 0
res = 0
hashmap = {}
n = len(s)
for tail in range(n):
if s[tail] in hashmap:
head = max(hashmap[s[tail]], head)
hashmap[s[tail]] = tail + 1
res = max(res, tail-head+1)
return res
python 未优化
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
head = 0
tail = 0
if len(s)<2:
return len(s)
res = 1
while tail<len(s)-1:
tail += 1
if s[tail] not in s[head:tail]:
res = max(tail-head+1, res)
else:
while s[tail] in s[head:tail]:
head += 1
return res