3. Longest Substring Without Repeating Characters
View on LeetCode ↗
C++
#include <algorithm>class Solution {public: int lengthOfLongestSubstring(string s) { set<char> mapping; int best = 0; int l = 0; for (int r = 0; r < s.size(); r++) { // not adding s[r] yet because we need to clean up the set for // s[r] to join while (mapping.find(s[r]) != mapping.end()) { // if this is the case, there is a duplicate in the // substring somewhere mapping.erase(s[l]); l++; } mapping.insert(s[r]); // now safe to add s[r] // after all dups are removed, we found a valid substring that // meets the condition, lets check with best best = max(best, r - l + 1); } return best; }};
had solved this already apparently but relearned it basic idea here is that you need to manage the state of your sliding window. be it you either insert the new input on the right first, or do move right pointer but fix the sliding window by moving left over until the sliding window can accept r. just need to be flexible
going to try implementing a new way