每个元音字母至少出现一次,并且包含 k 个辅音字母的子字符串的总数,我们可以使用滑动窗口来求解。
对于区间 [i,j) 内的子字符串,我们依次枚举子字符串的左端点 i,对于对应的右端点 j,我们不断地右移右端点 j,直到区间 [i,j) 对应的子字符满足每个元音字母至少出现一次,并且包含 k 个辅音字母(right)。再往右继续遍历直到找到多余的辅音字母(tmp)。此时以i位端点的子字符串数量为tmp-right+1;
public class 元音辅音字符串计数I {
public static void main(String[] args) {
System.out.println(countOfSubstrings("iqeaouqi", 2));
}
public static int countOfSubstrings(String word, int k) {
int n = word.length();
if(5+k>n) return 0;
Set<Character> set = Stream
.of('a','e','i','o','u')
.collect(Collectors.toSet());
HashMap<Character,Integer> map = new HashMap<>();
int right=0,ans=0,res=0;
for (int i = 0; i <n ; i++){
// 找到第一个满足字符串最小形式的位置
while(right<n && (map.size()<5 || ans<k)){
if(set.contains(word.charAt(right))){
map.put(word.charAt(right),map.getOrDefault(word.charAt(right),0)+1);
}else{
ans++;
}
right++;
}
// 判断循环结束没有字符串还是找到
if(map.size()==5 && ans==k){
int tmp = right;
// 如果是后面继续接'a','e','i','o','u',子字符串多加一
for(int j = right; j <= n; j++){
// 当最后一个字符符合时,tmp=j会被跳过;不判断会损失1位
if(j==n){
tmp=n;
break;
}
if(set.contains(word.charAt(j))){
continue;
}
tmp=j;
break;
}
res+=tmp-right+1;
}
if(set.contains(word.charAt(i))){
map.put(word.charAt(i),map.get(word.charAt(i))-1);
// 因为判断的是map的数量,当为0时,移除
if(map.get(word.charAt(i))==0){
map.remove(word.charAt(i));
}
}else{
ans--;
}
}
return res;
}
}