Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
To solve this problem, I used two pointers and hashmap. I add an example for illustration.
#include <string>
#include <iostream>
using namespace std;
// "abcabcbb" -> "abc"
// Two Pointers Method
int lengthOfLongestSubstring(string s) {
if(s.size() <= 1) return s.size();
bool map[256] = {false};
int i = 0;
int j = 0;
int maxLen = 0;
while(i < s.size()) {
if(!map[s[i]]) {
map[s[i]] = true;
i++;
} else {
maxLen = max(maxLen, i - j);
while(s[i] != s[j]) {
map[s[j]] = false;
j++;
}
i++;
j++;
}
}
maxLen = max(maxLen, i - j);
return maxLen;
}
int main(void) {
string test = "aab";
int len = lengthOfLongestSubstring(test);
cout << len << endl;
}