1
+ // 使用递归的思想,附上大神的解题思路,是在是太NB了
2
+ // https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/87768/4-lines-Python
3
+
4
+ // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Longest Substring with At Least K Repeating Characters.
5
+ // Memory Usage: 9.5 MB, less than 27.27% of C++ online submissions for Longest Substring with At Least K Repeating Characters.
6
+
7
+ class Solution
8
+ {
9
+ public:
10
+ int longestSubstring (string s, int k)
11
+ {
12
+ // 递归停止条件
13
+ if (k <= 0 || k > s.length ())
14
+ return 0 ;
15
+
16
+ vector<int > hashmap (128 , 0 );
17
+ for (char chr : s)
18
+ ++hashmap[chr];
19
+
20
+ for (char chr = ' a' ; chr <= ' z' ; ++chr)
21
+ {
22
+ if (hashmap[chr] < k && hashmap[chr] > 0 )
23
+ {
24
+ int res = 0 ;
25
+ for (int leftPtr = 0 , rightPtr = 0 ; leftPtr < s.length (); leftPtr = rightPtr + 1 , rightPtr = leftPtr)
26
+ {
27
+ while (rightPtr < s.length () && s[rightPtr] != chr)
28
+ ++rightPtr;
29
+
30
+ res = max (res, longestSubstring (s.substr (leftPtr, rightPtr - leftPtr), k));
31
+ }
32
+
33
+ return res;
34
+ }
35
+ }
36
+
37
+ return s.length ();
38
+ }
39
+ };
40
+
41
+ // 下面是自己写的真n2的时间复杂度的,果然是非常的慢
42
+ // Runtime: 636 ms, faster than 5.05% of C++ online submissions for Longest Substring with At Least K Repeating Characters.
43
+ // Memory Usage: 10.9 MB, less than 27.27% of C++ online submissions for Longest Substring with At Least K Repeating Characters.
44
+
45
+ class Solution
46
+ {
47
+ public:
48
+ int longestSubstring (string s, int target)
49
+ {
50
+ int res = 0 ;
51
+ for (int i = 0 ; i < s.length (); ++i)
52
+ {
53
+ vector<int > hashmap (26 , 0 );
54
+ for (int j = i; j < s.length (); ++j)
55
+ {
56
+ ++hashmap[s[j] - ' a' ];
57
+
58
+ bool ok = true ;
59
+ for (int k = 0 ; k < 26 ; ++k)
60
+ {
61
+ if (hashmap[k] > 0 && hashmap[k] < target)
62
+ {
63
+ ok = false ;
64
+ break ;
65
+ }
66
+ }
67
+
68
+ if (ok) res = max (res, j - i + 1 );
69
+ }
70
+ }
71
+ return res;
72
+ }
73
+ };
0 commit comments