题目描述

2062. 统计字符串中的元音子字符串

题解

此题是一道简单的字符串匹配题,1.暴力求解 2.滑动窗口(待补充)

代码参考:

暴力求解

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
class Solution {
public int countVowelSubstrings(String word) {
//1.字符串子串问题,暴力枚举
if (word.length() < 5) {
return 0;
}
int len = word.length();
int count = 0;
for (int i = 0; i < len; i++) {
int num = 0;
for (int j = i; j < len; j++) {
//普通比较
// if (!checkVowel(word.charAt(j))) {
// break;
// }
// set.add(word.charAt(j));
// if (set.size() == 5) {
// count++;
// }
//位运算优化,参考字符串hash
char c = word.charAt(j);
if (c == 'a') {
num = (num | 1);
} else if (c == 'e') {
num = num | (1 << 1);
} else if (c == 'i') {
num = num | (1 << 2);
} else if (c == 'o') {
num = num | (1 << 3);
} else if (c == 'u') {
num = num | (1 << 4);
} else {
break;
}
if (num == 31) {
count++;
}
}
}
return count;
}

//必须是元音字符
//此处可转化为位运算,参考字符串hash
private boolean checkVowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
return true;
}
return false;
}
}

滑动窗口

待补充