LeetCode 3 题 : The oldest string without repeating characters
3. The oldest string without repeating characters
First attempt to implement in c++, to remember
1. C++ implementation (found not applicable) :
class Solution { public: int lengthOfLongestSubstring(string s) { int length = s.size(); unordered_map<int, int> hashtable; int lastIndex = 0; int maxlen = 0; for (int i = 0; i < length; If (hashtable.find(s[I])! = hashtable.end()) { maxlen = max(maxlen, i - lastIndex); hashtable.clear(); lastIndex = i + 1; } else { hashtable[s[i]] = true; } } return maxlen; }};Copy the code
Another official implementation:
class Solution { public: int lengthOfLongestSubstring(string s) { unordered_set<char> occ; int n = s.size(); int right = 0, ans = 0; for (int i = 0; i < n; ++i) { if ( i ! = 0) { occ.erase(s[i - 1]); } while(right < n && ! occ.count(s[right])) { occ.insert(s[right]); ++right; } ans = max(ans, right - i); } return ans; }};Copy the code