Skip to content

Commit 46dbe0c

Browse files
committed
Update and rename lengthOfLongestSubstring.cpp to longest-substring-without-repeating-characters.cpp
1 parent 4497e87 commit 46dbe0c

File tree

2 files changed

+25
-21
lines changed

2 files changed

+25
-21
lines changed

C++/lengthOfLongestSubstring.cpp

Lines changed: 0 additions & 21 deletions
This file was deleted.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int lengthOfLongestSubstring(string s) {
7+
// Record the last occurrence of each char.
8+
unordered_map<char, size_t> last_occurrence;
9+
size_t starting_idx = 0, ans = 0;
10+
for (size_t i = 0; i < s.size(); ++i) {
11+
auto it(last_occurrence.find(s[i]));
12+
if (it == last_occurrence.cend()) {
13+
last_occurrence.emplace_hint(it, s[i], i);
14+
} else { // s[i] appeared before. Check its validity.
15+
if (it->second >= starting_idx) {
16+
ans = max(ans, i - starting_idx);
17+
starting_idx = it->second + 1;
18+
}
19+
it->second = i;
20+
}
21+
}
22+
ans = max(ans, s.size() - starting_idx);
23+
return ans;
24+
}
25+
};

0 commit comments

Comments
 (0)