-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode1456.java
More file actions
82 lines (74 loc) · 2.42 KB
/
LeetCode1456.java
File metadata and controls
82 lines (74 loc) · 2.42 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
public class LeetCode1456 {
public static void main(String[] args) {
// 输入:s = "abciiidef", k = 3
// 输出:3
System.out.println(new Solution1456_2().maxVowels("abciiidef", 3));
// 输入:s = "aeiou", k = 2
// 输出:2
System.out.println(new Solution1456_2().maxVowels("aeiou", 2));
// 输入:s = "leetcode", k = 3
// 输出:2
System.out.println(new Solution1456_2().maxVowels("leetcode", 3));
// 输入:s = "rhythms", k = 4
// 输出:0
System.out.println(new Solution1456_2().maxVowels("rhythms", 4));
// 输入:s = "tryhard", k = 4
// 输出:1
System.out.println(new Solution1456_2().maxVowels("tryhard", 4));
}
}
/**
* DP复杂度为O(nk),会超时(102/106)
*/
class Solution1456_1 {
public int maxVowels(String s, int k) {
boolean[] vowels = new boolean[s.length()];
int[] dp = new int[s.length()];
int ans = 0;
// 初始化
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels[i] = true;
dp[i] = 1;
ans = 1;
}
}
for (int len = 2; len <= k; len++) {
for (int i = dp.length - 1; i >= len - 1; i--) {
dp[i] = dp[i - 1];
if (vowels[i]) {
dp[i]++;
ans = Math.max(ans, dp[i]);
if (ans == k) {
return k;
}
}
}
}
return ans;
}
}
class Solution1456_2 {
public int maxVowels(String s, int k) {
boolean[] vowels = new boolean[s.length()]; // NOTE: 也可以不提前判断,因为大部分元素只判断一次
// 初始化
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels[i] = true;
}
}
int count = 0;
for (int i = 0; i < k; i++) {
count += vowels[i] ? 1 : 0;
}
int ans = count;
for (int i = k; i < s.length(); i++) {
count -= vowels[i - k] ? 1 : 0;
count += vowels[i] ? 1 : 0;
ans = Math.max(count, ans);
}
return ans;
}
}