元音辅音字符串计数 I

        每个元音字母至少出现一次,并且包含 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值