-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_0467_findSubstringInWraproundString.cc
More file actions
59 lines (54 loc) · 1.25 KB
/
Copy pathProblem_0467_findSubstringInWraproundString.cc
File metadata and controls
59 lines (54 loc) · 1.25 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
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int findSubstringInWraproundString(string s)
{
// cnt[c]的含义为:
// 必须以c字符为结尾,符合条件的子串最大长度
vector<int> cnt(256);
int n = s.length();
cnt[s[0]] = 1;
// 前一个字符成长的长度
int len = 1;
for (int i = 1; i < n; i++)
{
char pre = s[i-1];
char cur = s[i];
if ((pre == 'z' && cur == 'a') || pre == cur - 1)
{
// 是连续的
len++;
}
else
{
len = 1;
}
cnt[cur] = std::max(cnt[cur], len);
}
// 答案,s中有多少不同的非空子串,也是想象串的子串
int ans = 0;
for (int i = 0; i < 256; i++)
{
// 对于长度为4的子串 abcd,刚好有 4 个子串满足条件, a、ab、abc、abcd
ans += cnt[i];
}
return ans;
}
};
void testFindSubstringInWraproundString()
{
Solution s;
EXPECT_EQ_INT(1, s.findSubstringInWraproundString("a"));
EXPECT_EQ_INT(2, s.findSubstringInWraproundString("cac"));
EXPECT_EQ_INT(6, s.findSubstringInWraproundString("zab"));
EXPECT_SUMMARY;
}
int main()
{
testFindSubstringInWraproundString();
return 0;
}