Skip to content

Commit 029e6f3

Browse files
committed
AC P395 每日一题
1 parent feaa970 commit 029e6f3

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

P395.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include "header.h"
2+
#include <array>
3+
#include <cstring>
4+
#include <ostream>
5+
#include <string>
6+
7+
class Solution {
8+
private:
9+
int dfs(const string& s, int l, int r, int k) {
10+
array<int, 26> cnt;
11+
cnt.fill(0);
12+
int i;
13+
for (i=l; i<=r; i++)
14+
cnt[s[i]-'a']++;
15+
char split = 0;
16+
for (i=0; i<26; i++) {
17+
if (cnt[i]>0 && cnt[i]<k) {
18+
split = i+'a';
19+
break;
20+
}
21+
}
22+
if (split==0) return r-l+1;
23+
i=l;
24+
int ret =0;
25+
while (i<=r) {
26+
while (i<=r && s[i]==split) i++;
27+
if (i>r) break;
28+
int start =i;
29+
while (i<=r && s[i]!=split) i++;
30+
int &&len = dfs(s, start, i-1, k);
31+
ret = max(ret, len);
32+
}
33+
return ret;
34+
}
35+
public:
36+
int longestSubstring(string s, int k){
37+
return dfs(s, 0, s.length()-1, k);
38+
}
39+
};
40+
41+
int main() {
42+
string s;
43+
int k;
44+
s = "aaabb";
45+
k = 3;
46+
cout << Solution().longestSubstring(s, k) << endl;
47+
48+
s = "ababbc";
49+
k=2;
50+
cout << Solution().longestSubstring(s, k) << endl;
51+
s = "bbaaacbd";
52+
k=3;
53+
cout << Solution().longestSubstring(s, k) << endl;
54+
55+
s = "aaaaaaaaabbbcccccddddd";
56+
k=5;
57+
cout << Solution().longestSubstring(s, k) << endl;
58+
s = "zzzzzzzzzzaaaaaaaaabbbbbbbbhbhbhbhbhbhbhicbcbcibcbccccccccccbbbbbbbbaaaaaaaaafffaahhhhhiaahiiiiiiiiifeeeeeeeeee";
59+
k = 10;
60+
cout << Solution().longestSubstring(s, k) << endl;
61+
return 0;
62+
}

0 commit comments

Comments
 (0)