-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16.lengthOfLongestSubstring.cpp
More file actions
executable file
·100 lines (90 loc) · 2.77 KB
/
Copy path16.lengthOfLongestSubstring.cpp
File metadata and controls
executable file
·100 lines (90 loc) · 2.77 KB
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
90
91
92
93
94
95
96
97
98
99
100
/*
@filename 16.cpp
@author caonan
@date 2022-03-28 14:45:21
@reference 剑指offer专项
@url https://leetcode-cn.com/problems/wtcaE1/
@brief 给定一个字符串 s ,请你找出其中不含有重复字符的 最长连续子字符串的长度。
*/
#include <cassert>
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int max_len = 0;
unordered_set<char> map_store;
int left = 0;
for (int right = 0; right < s.size();) {
if (map_store.find(s[right]) == map_store.end()) {
map_store.insert(s[right]);
max_len = std::max(max_len, right - left + 1);
++right;
} else {
map_store.erase(s[left++]);
}
}
return max_len;
}
// asii码有最多256个,可以用固定大小的的数组表示
int lengthOfLongestSubstring1(string s) {
vector<int> counts(256, 0);
// 每次都遍历了整个数组,效率不高
auto is_greater_than1 = [](const vector<int>& counts) -> bool {
for (const auto& v : counts) {
if (v > 1) {
return true;
}
}
return false;
};
int left = -1;
int max_len = 0;
for (int right = 0; right < s.size(); ++right) {
counts[s[right]]++;
while (is_greater_than1(counts)) {
++left;
counts[s[left]]--;
}
max_len = std::max(max_len, right - left);
}
return max_len;
}
// 在lengthOfLongestSubstring1的基础上优化掉遍历counts的开销
// 因为右边每次加入新元素,如果有重复,那必然大于1,于是left右移直到将counts[s[right]]减下去
int lengthOfLongestSubstring2(string s) {
vector<int> counts(256, 0);
int left = -1;
int max_len = 0;
for (int right = 0; right < s.size(); ++right) {
counts[s[right]]++;
while (counts[s[right]] > 1) {
++left;
counts[s[left]]--;
}
max_len = std::max(max_len, right - left);
}
return max_len;
}
};
int main() {
Solution s;
assert(s.lengthOfLongestSubstring("abcabcbb") == 3);
assert(s.lengthOfLongestSubstring("bbbbb") == 1);
assert(s.lengthOfLongestSubstring("pwwkew") == 3);
assert(s.lengthOfLongestSubstring("tmmzuxt") == 5);
assert(s.lengthOfLongestSubstring1("abcabcbb") == 3);
assert(s.lengthOfLongestSubstring1("bbbbb") == 1);
assert(s.lengthOfLongestSubstring1("pwwkew") == 3);
assert(s.lengthOfLongestSubstring1("tmmzuxt") == 5);
assert(s.lengthOfLongestSubstring2("abcabcbb") == 3);
assert(s.lengthOfLongestSubstring2("bbbbb") == 1);
assert(s.lengthOfLongestSubstring2("pwwkew") == 3);
assert(s.lengthOfLongestSubstring2("tmmzuxt") == 5);
return 0;
}