3. Longest Substring Without Repeating Characters
I solved this problem using C++.
My idea: use unordered_set to store the characters in the substring and use two pointers to iterate through the string.
1 | class Solution |
e.g.
input: s = “pwwkew”
output: 3
- lt = 0, rt = 0, maxLength = 0, charSet = {}
- charSet.insert(‘p’), rt = 1
- charSet.insert(‘w’), rt = 2
- s[rt] = ‘w’, charSet.find(‘w’) != charSet.end()
4.1. maxLength = max(0, 2 - 0) = 2
4.2. search for ‘w’ in the set, if not found, erase the character from the set
4.3. i = 0, s[i] = ‘p’, charSet.erase(‘p’)
4.4. i = 1, s[i] = ‘w’, lt = i + 1 = 2
4.5. charSet.insert(s[rt]), and rt++, now charSet = {‘w’} and ‘p’ is erased - charSet.insert(‘k’), rt = 3
- charSet.insert(‘e’), rt = 4
- charSet.insert(‘w’), rt = 5
- s[rt] = ‘w’, charSet.find(‘w’) != charSet.end()
8.1. maxLength = max(2, 5 - 2) = 3
8.2. search for ‘w’ in the set, if not found, erase the character from the set
8.3. i = 2, s[i] = ‘w’, lt = i + 1 = 3
8.4. charSet.insert(s[rt]), and rt++, now charSet = {‘k’, ‘e’} and ‘w’ is erased - now rt = 6 and rt < s.size() is false, return max(3, 6 - 3) = 3
conclusion
I remembered this problem when I was grade 1 in college, and I found it difficult to solve at that time.
Now I can solve it quickly…😏😋