https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//滑动窗口裸题
//s 由英文字母、数字、符号和空格组成 ????????
if(s == ""){
return 0;
}
s = ' ' + s;
//cout << s << '\n';
int len = s.size();
int a[50010];
int tmp[300];
for(int i = 0 ; i < 300 ; i++){
tmp[i] = 0;
}
for(int i = 1 ; i < len ; i++) {
//确定前一个相同字母位置
//cout << s[i] - 'a' << ' ' << tmp[s[i] - 'a'] <<"?\n";
if(tmp[s[i]] == 0){
a[i] = 0;
tmp[s[i]] = i;
}
else {
a[i] = tmp[s[i]];
tmp[s[i]] = i;
}
//cout << a[i] << '\n';
}

int ans = 1;
int top, end;
top = end = 1;
for(int i = 2; i < len ; i++){
if(a[i] < top){
end++;
ans = max(ans, end - top + 1);
}
else if(a[i] == top){
top++;
end++;
ans = max(ans, end - top + 1);
}
else {
top = a[i] + 1;
end++;
ans = max(ans, end - top + 1);
}
}
return ans;
}
};