Tags: LeetCode DSA Sliding Window
Prompt
Given a string s, find the length of the longest substring without duplicate characters.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = “zxyzxyz”
Output: 3
Explanation: The string “xyz” is the longest without duplicate characters.
Solution:
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int left = 0;
int returnCount = 0;
std::unordered_set<int> dupeSet;
for(int i = 0; i<s.size(); i++)
{
while(dupeSet.contains(s[i]))
{
dupeSet.erase(s[left]);
left++;
}
dupeSet.insert(s[i]);
returnCount = max(returnCount, i-left+1);
}
return returnCount;
}
};
Explanation
So this is a sliding window problem, and basically what it has here is two points, one that is considered the left, and the other the right. Right is represented by the i in the for loop and then left is the variable left
Basically what you do here, is you append a value to a hashset each loop, so you increase right by one. Doing so gives you a new longest substring, this being r-l, which you check at the end of the loop.
You then have this while loop inside of there, and what that does is it checks to see if the current character at the right index is already in your set of known characters. If it is, then what you need to do is go to the point where this is no longer the case. So you increment the left and remove the value at left from the set, until the set is valid again.
This way you are able to slide and change the size of the window based on the idea of this set adding an element until it finds a duplicate one, and then it corrects itself.