3.lengthOfLongestSubstring

code

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

/*
滑动窗口
1.遍历string 用hash存储每个char出现的次数
2.每次记录最大的length 当出现重复元素时 移动left去重
3.更新length = right - left + 1
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0;
int l = 0,r = 0;
unordered_map<char,int> cnt;
int n = s.size();
for (;r < n;r++) {
cnt[s[r]]++;
while (cnt[s[r]] > 1) { //去重操作
cnt[s[l]]--; //先在hashTable中修改
l++; //移动left
}
ans = max(ans,r-l+1); //uodate longest length
}
return ans;
}
};
/*
review 2024.2.23
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char,int> record;
int cnt = 0;
int ret = 0;
for (int j = 0,i = 0;j < s.size();j++) {
record[s[j]]++;
cnt++;
while (record[s[j]] > 1) {
record[s[i++]]--;
cnt--;
}
ret = max(cnt,ret);
}
return ret;
}
};
/*
review 6.19
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> hash;
int ans = 0;
for (int l = 0,r = 0;r < s.size();r++) {
while (hash.find(s[r]) != hash.end()) {
hash.erase(s[l]);
l++;
}
hash.insert(s[r]);
ans = max(ans,r - l + 1);
}
return ans;
}
};
/*
review 2024.7.8
*/

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int l = 0,r = 0;
unordered_set<int> hash;
int ret = 0;
for (;r < s.size();r++) {
while (hash.contains(s[r])) { //c++20
hash.erase(s[l++]);
}
hash.insert(s[r]);
ret = max(ret,r - l + 1);
}
return ret;
}
};

3.lengthOfLongestSubstring
https://williammarioalan.github.io/2025/01/29/3-lengthOfLongestSubstring/
Author
mario
Posted on
January 29, 2025
Licensed under