#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;
}
Is the time complexity O(n)
or O(n^2)
? Why?
My intuition is that it's O(n), i and j iterate across the same length.