1. we keep moving one pointer and count each character until one character has been counted before, i.e. the count for the character is one already.
2. Then we move another pointer and decrease the counter for each character until the character pointed by the first pointer has count 0.
3. And then leave the second pointer there and move the first pointer again. Repeat step 1-2 until the first pointer reaches the end.
1: class Solution {
2: public:
3: int lengthOfLongestSubstring(string s) {
4: vector<int> chars(256, 0);
5: int i = 0, j = 0, maxLen = 0;
6: while (i < s.size()) {
7: while (i < s.size() && chars[s[i]] == 0) {++chars[s[i++]];};
8: maxLen = max(maxLen, i - j);
9: while (i < s.size() && chars[s[i]] == 1) --chars[s[j++]];
10: }
11: return maxLen;
12: }
13: };
No comments:
Post a Comment