Longest String
Given a string s, find the length of the longest without duplicate characters.
Solution
The solution uses hash-maps-1754999036 to find repeating characters to identify the string.
left and right are two variables used to define the index of ends of the string, right traverses through the string in a loop. When a repeating
character is found, length is updated and the left is moved to right + 1 for start of the new substring.
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char,int> lastSeen;
int left = 0, longest = 0;
for (int right = 0; right < s.size(); right++) {
if (lastSeen.count(s[right]) && lastSeen[s[right]] >= left) {
// Move left boundary past the duplicate
left = lastSeen[s[right]] + 1;
}
lastSeen[s[right]] = right;
longest = max(longest, right - left + 1);
}
return longest;
}
};