leetcode-3-字符串题-无重复字符的最长字串

题目

1.png

解法

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
53
54
55
// 滑动窗口
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
if(s.empty()) return 0;
if(n == 1) return 1;

unordered_map<char, int> charIndex;
int maxLen = 0;

for(int i = 0, j = 0; j < n; ++j){
if(charIndex.count(s[j]) > 0){
i = max(i, charIndex[s[j]]);
charIndex[s[j]] = j+1;
}else{
charIndex.insert({s[j], j+1});
}
maxLen = max(maxLen, j-i+1);
}

return maxLen;
}
};

// 动态规划
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
if(s.empty()) return 0;
if(n == 1) return 1;

unordered_map<char, int> charIndex;
int curLen = 0;
int maxLen = 0;

for(int i = 0; i < n; ++i){
if(charIndex.count(s[i]) > 0){
if(i - charIndex[s[i]] > curLen){
++curLen;
}else{
if(curLen > maxLen) maxLen = curLen;
curLen = i - charIndex[s[i]];
}
charIndex[s[i]] = i;
}else{
++curLen;
charIndex.insert({s[i], i});
}
}
if(curLen > maxLen) maxLen = curLen;
return maxLen;
}
};