-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_1371_findTheLongestSubstring.cc
80 lines (74 loc) · 1.54 KB
/
Problem_1371_findTheLongestSubstring.cc
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
#include <algorithm>
#include <string>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int findTheLongestSubstring(string s)
{
int n = s.length();
// 只有5个元音字符,状态就5位
vector<int> map(32);
// map[0...31] = -2
// map[01100] = -2, 这个状态之前没出现过
std::fill(map.begin(), map.end(), -2);
map[0] = -1;
int ans = 0;
for (int i = 0, status = 0, m; i < n; i++)
{
// status : 0....i-1字符串上,aeiou的奇偶性
// s[i] = 当前字符
// 情况1 : 当前字符不是元音,status不变
// 情况2 : 当前字符是元音,a~u(0~4),修改相应的状态
m = move(s[i]);
if (m != -1)
{
status ^= (1 << m);
}
// status: 0....i字符串上,aeiou的奇偶性
// 同样的状态,之前最早出现在哪
if (map[status] != -2)
{
ans = std::max(ans, i - map[status]);
}
else
{
map[status] = i;
}
}
return ans;
}
int move(char c)
{
switch (c)
{
case 'a':
return 0;
case 'e':
return 1;
case 'i':
return 2;
case 'o':
return 3;
case 'u':
return 4;
default:
return -1;
}
}
};
void test()
{
Solution s;
EXPECT_EQ_INT(13, s.findTheLongestSubstring("eleetminicoworoep"));
EXPECT_EQ_INT(5, s.findTheLongestSubstring("leetcodeisgreat"));
EXPECT_EQ_INT(6, s.findTheLongestSubstring("bcbcbc"));
EXPECT_SUMMARY;
}
int main()
{
test();
return 0;
}