c++ 使用hashmap+ 滑动窗口
踩坑:map的存储不是按照插入的顺序来进行存储的,而是经过排序的,因此不能使用hashmap.erase(hashmap.begin(),iter)来进行范围删除时间复杂度为O( n 2 n^{2} n2)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char, int> hashmap;
map<char, int>::iterator iter;
int left = 0, right = 0;
int n = s.size();
int ans = 0;
for (int i = 0; i < n; ++i) {
if(hashmap.count(s[i]) == 0){
hashmap.insert(pair<char,int>(s[i],i));
right = i; // 右指针右移
if(right - left + 1 > ans){
ans = right - left + 1;
}
}
else{ //如果存在了
if(right - left + 1 > ans){
ans = right - left + 1;
}
iter = hashmap.find(s[i]);
int itsecond = iter->second;
for (int j = left; j <= itsecond; ++j) {
hashmap.erase(s[j]);
}
left = itsecond + 1;
hashmap.insert(pair<char,int>(s[i],i));
right = i; // 右指针右移
}
}
return ans;
}
};
BUG:
ERROR: AddressSanitizer: heap-use-after-free on address·····
原代码:
iter = hashmap.find(s[i]);
for (int j = left; j <= iter->second; ++j) {
hashmap.erase(s[j]);
}
left = iter->second + 1;
改进后:
iter = hashmap.find(s[i]);
int itsecond = iter->second;
for (int j = left; j <= itsecond; ++j) {
hashmap.erase(s[j]);
}
left = itsecond + 1;
分析: iter指向的元素在删除后,变为野指针,所以报 使用了已经释放的地址!
python 实现
方法差不多,python的好写一点,但是速度慢
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
start = -1
end = 0
length = len(s)
dic = {} # hashmap
max_len = 0
for i in range(length):
if s[i] in dic:
start = max(dic[s[i]], start)
dic[s[i]] = i # 更新
max_len = max(max_len, end - start)
end = end + 1
return max_len