Skip to content

Commit 0ee9369

Browse files
committed
Add 'Longest Substring Without Repeating Characters' solution.
1 parent 2a97f35 commit 0ee9369

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
Longest Substring Without Repeating Characters
3+
4+
Given a string, find the length of the longest substring without repeating
5+
characters. For example, the longest substring without repeating letters for
6+
"abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring
7+
is "b", with the length of 1.
8+
*/
9+
10+
class Solution {
11+
public:
12+
int lengthOfLongestSubstring(string s) {
13+
// String only contains ASCII characters.
14+
// The function of array isAppeared equals to hash.
15+
bool isAppeared[256];
16+
for (int i=0; i<256; i++)
17+
isAppeared[i] = false;
18+
19+
// To maintain a sliding window, in where each characters at most appears
20+
// once.
21+
int l = 0, r = 0, result = 0;
22+
while (r < s.length()) {
23+
while (isAppeared[s[r]]) {
24+
isAppeared[s[l]] = false;
25+
l++;
26+
}
27+
isAppeared[s[r]] = true;
28+
if (r - l + 1 > result)
29+
result = r - l + 1;
30+
r++;
31+
}
32+
return result;
33+
}
34+
};

0 commit comments

Comments
 (0)