[LeetCode] Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

  • new solution update 2022.02.14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int arr[128]{false};
int res = 0;
for(int l=0, r = 0; r < s.length(); r++) {
while(arr[s[r]]) {
arr[s[l++]]--;
}
arr[s[r]]++;
res = max(res, r - l + 1);
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int result = 0;
int current = 1;
bool isChecked[128] = {false};
int head = 0, tail = 0;

for(tail = 0; tail < s.length(); tail++, current++) {
if(isChecked[s[tail]]) {
while(s[head] != s[tail]) {
isChecked[s[head++]] = false;
current--;
}
head++;
current--;
} else {
isChecked[s[tail]] = true;
}
if(result < current)
result = current;
}

return result;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/07/PS/LeetCode/Longest-Substring-Without-Repeating-Characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.