题目:无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
要查找无重复字符的最长子串,至少要从左往右扫描一遍。
为了确定字符串有无重复及重复的位置,我使用哈希表来存储扫描过的字符。如果在扫描过程中遇到 了重复的,就退回重复字符的下一个字符,重新开始扫描。这样逐个找出所有无重复的字符串,从中选出最长的。
使用这种方法,只有一个索引i,每次遇到重复,i都会回溯,从而浪费了相当多的时间。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char,int> hash;
int n = s.size();
int temp = 0, ans = 0;
for(int i = 0; i < n; i++) {
auto p = hash.find(s[i]);
if (p == hash.end()) {
temp++;
}
else if(p != hash.end()){
if (temp > ans)
ans = temp;
temp = 1;
i = p -> second + 1;
hash.clear();
}
hash[s[i]] = i;
if (temp > ans)
ans = temp;
}
return ans;
}
};
官方给出的题解中提到了滑动窗口的方法,窗口中是无重复的字符子串。定义一个窗口,如果索引i到j-1是没有重复的,就只需要检查s[j]对于的字符是否存在于字符串
中。使用滑动窗口,有两个索引i,j。我们向右侧滑动j,如果它不在我们构建的哈希表中,就继续把j向右滑动。如果s[j]存在于哈希表中,就说明我们已经找到了以索引i开头的最长无重复子串。该子串的长度为(j-i)。重复以上过程,对所有的i这样做,就可以得到答案。
使用这种方法,当i向右滑动时,中一定是无重复的,因此j可以继续向右滑动。这样,i和j最多只需要各自遍历一遍字符串s,时间复杂度为:
。改进后的代码如下所示:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char,int> hash;
int n = s.size();
int ans = 0, i = 0, j = 0;
while (i < n && j < n){
auto p = hash.find(s[j]);
if (p == hash.end()) {
hash[s[j++]] = j;
ans = max(ans, j-i);
}
else {
hash.erase(s[i++]); //删除hash中重复的元素
}
}
return ans;
}
};
滑动窗口的方法还可以继续优化。如果s[j]在范围内有与j'重复的字符,可以直接将变为j'+1。这样仅仅需要n个步骤就可以完成。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char,int> hash;
int n = s.size();
int ans = 0, i = 0, j = 0;
while (i < n && j < n){
auto p = hash.find(s[j]);
if (p != hash.end())
i = max(p -> second+1, i); //窗口外的重复的字符不会影响到i
ans = max(ans, j-i+1);
hash[s[j++]] = j;
}
return ans;
}
};