#include<string> #include<unordered_set> #include<algorithm> using std::string; using std::unordered_set;
// Given a string s, find the length of the longest substring without repeating characters. classSolution { public: intlengthOfLongestSubstring(string s) { int i = 0, j = 0; int n = s.size(); unordered_set<char> uset; int len = 0;
for (j = 0; j < n; j++) { if (uset.count(s[j])) { len = std::max(len, (int)uset.size()); // Shrink left boundary while (s[i] != s[j]) { uset.erase(s[i]); i++; } if (s[i] == s[j]) { //Until the current substring is removed uset.erase(s[i]); i++; } } uset.insert(s[j]); } return std::max(len, (int)uset.size()); } };
leetcode hot 100 rewrite: Before entering the loop, first shrink the left boundary until it satisfies that it is a substring without repeating characters.