Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save zhoutuo/4751922 to your computer and use it in GitHub Desktop.

Select an option

Save zhoutuo/4751922 to your computer and use it in GitHub Desktop.
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unsigned int result = 0;
set<char> table;
queue<char> substr;
for(int i = 0; i < s.length(); ++i) {
if(table.find(s[i]) != table.end()) {
while(substr.front() != s[i]) {
table.erase(substr.front());
substr.pop();
}
substr.pop();
} else {
table.insert(s[i]);
}
substr.push(s[i]);
result = max(result, substr.size());
}
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment