给你一个字符串 word
和一个 非负 整数 k
。
返回 word
的 子字符串 中,每个元音字母('a'
、'e'
、'i'
、'o'
、'u'
)至少 出现一次,并且 恰好 包含 k
个辅音字母的子字符串的总数。
示例 1:
输入:word = "aeioqq", k = 1
输出:0
解释:
不存在包含所有元音字母的子字符串。
示例 2:
输入:word = "aeiou", k = 0
输出:1
解释:
唯一一个包含所有元音字母且不含辅音字母的子字符串是 word[0..4]
,即 "aeiou"
。
示例 3:
输入:word = "ieaouqqieaouqq", k = 1
输出:3
解释:
包含所有元音字母并且恰好含有一个辅音字母的子字符串有:
word[0..5]
,即"ieaouq"
。word[6..11]
,即"qieaou"
。word[7..12]
,即"ieaouq"
。
提示:
5 <= word.length <= 250
word
仅由小写英文字母组成。0 <= k <= word.length - 5
分析:由于字符串长度不超过250,暴力法也可以解决,这里使用滑动窗口法。从左向右遍历字符串,直到满足条件。再从当前窗口的左端点向右移动,检查有多少个符合要求的子串。之后继续遍历,如果符合条件,则加上子串数量,同时继续检查有多少符合要求的子串;如果不符合条件,将子串数量重置。
注意遍历完成后,还要再检查一次当前的窗口是否符合条件。
int judge(char c)
{if(c=='a')return 0;if(c=='e')return 1;if(c=='i')return 2;if(c=='o')return 3;if(c=='u')return 4;return 5;
}
int countOfSubstrings(char* word, int k) {int ans=0,l=0,cnt=5,len=strlen(word),power=0;int sum[6]={0};for(int i=0;i<len;++i){int index=judge(word[i]);if(index<=4){if(sum[index]==0)cnt--;sum[index]++;}else if(index==5){if(sum[index]==k){ans+=power;for(;l<=i;++l){int pos=judge(word[l]);if(pos<=4){sum[pos]--;if(sum[pos]==0)cnt++;}else if(pos==5){sum[pos]--;if(sum[pos]<=k)break;}}power=0;if(sum[5]<k)sum[index]++,l++;}else sum[index]++;}if(sum[5]==k&&cnt==0){int temp[6]={0};for(int j=0;j<6;++j)temp[j]=sum[j];for(int j=l;j<i;++j){power++;int pos=judge(word[j]);temp[pos]--;if((pos<=4&&temp[pos]==0)||temp[5]<k)break;}}//printf("i=%d l=%d cnt=%d ans=%d k=%d pow=%d\n",i,l,cnt,ans,sum[5],power);}ans+=power;return ans;
}