leetcode结果与本地不一致
题目:3. 无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
代码
代码片
#include<unordered_map>
#include<algorithm>
#include<iostream>
#include<string>
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int rmax = 0;
unordered_map<char, int> hmap;
hmap.clear();
for (int i = 0; i < s.size(); i++) {
auto point = hmap.find(s[i]);
if (point == hmap.end()) {
hmap.insert({ s[i],i });
rmax = max(rmax, (int)hmap.size());
}
else {
hmap.insert({ s[i],i });
hmap.erase(hmap.begin(), point);
rmax = max(rmax, (int)hmap.size());
}
std::cout<<rmax<<" "<<hmap.size()<<" "<<s[i]<<endl;
}
return rmax;
}
};
结果
错误分析
测试用例:s = “pwwkew”
预期输出:3
leetcode输出:4
本地输出:3
输出rmax和hmap.size()看看问题出在哪里
leetcode:
本地:
当第二次输入 w
的时候hmap.size()理应为1,而leetcode为2。把hmap打印出来看看。
unordered_map.insert()
,这个函数在leetcode中是在数据头
插入的,而在VS本地是在数据尾
插入的,这不是坑爹吗。把
hmap.erase(hmap.begin(), point);
改为
hmap.erase(point,hmap.end());
就好了。但是还是不能通过所有用例,新的问题暂时没有解决。