LeetCode第三题:无重复字符的最长子串
第一次尝试用c++实现,纪念一下
1. c++实现(发现有不适用的情况):
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int length = s.size();
unordered_map<int, int> hashtable;
int lastIndex = 0;
int maxlen = 0;
for (int i = 0; i < length; i++) {
// 找到了重复了
if (hashtable.find(s[i]) != hashtable.end()) {
maxlen = max(maxlen, i - lastIndex);
hashtable.clear();
lastIndex = i + 1;
} else {
hashtable[s[i]] = true;
}
}
return maxlen;
}
};
换一种官方的实现方案:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> occ;
int n = s.size();
int right = 0, ans = 0;
for (int i = 0; i < n; ++i) {
if ( i != 0) {
occ.erase(s[i - 1]);
}
while(right < n && !occ.count(s[right]))
{
occ.insert(s[right]);
++right;
}
ans = max(ans, right - i);
}
return ans;
}
};