1456. Maximum Number of Vowels in a Substring of Given Length

Link

Solution

先找出初始區間 (0...k-1)的vowel 有幾個 記錄在count值。

接下來移動區間對count值加減。

    public int maxVowels(String s, int k) {
        int count = 0, max = 0;
        for(int i = 0; i < k; i++){
            if(isVowel(s.charAt(i))){
                count++;
            }
        }
        max = count;
        for(int i = k; i < s.length(); i++){
            
            if(isVowel(s.charAt(i))) count++;
            if(isVowel(s.charAt(i-k))) count--;
            max = Math.max(count, max);
        }
        return max;
        
    }
    
    
    public boolean isVowel(char c){
        if(c == 'a' || c == 'e' || c == 'o' || c == 'i' || c == 'u'){
            return true;
        }
        return false;
    }
    

Last updated

Was this helpful?