#include <unordered_map>
using namespace std;
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> ht;
int max = 0;
int i = 0; int j = 0;
while (i < s.size() && j < s.size()) {
if (ht.find(s.at(j)) == ht.end()) {
ht.insert( {s.at(j), j} );
max = (j - i + 1 > max) ? j - i + 1 : max;
j++;
}
else {
int len = ht.at(s.at(j)) + 1;
while(i < len) {
ht.erase(s.at(i));
i++;
}
}
}
return max;
}
时间复杂度是O(n)
还是O(n^2)
?为什么?
我的直觉是它是O(n),i和j重复相同的长度。