Maximum Number of Vowels in a Substring of Given Length - LeetCode
문자열 s와 정수 k가 주어집니다. 문자열 s의 부분 문자열 중 길이가 k인 부분 문자열에서 최대 모음(모음 글자) 개수를 반환하세요.
영어에서의 모음 글자는 'a', 'e', 'i', 'o', 'u' 입니다.
Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.
문제 요약:
주어진 문자열에서 길이가 k인 부분 문자열 중에서 최대 모음 개수를 찾는 문제입니다.
풀이과정:
문자열 s를 순회하면서 길이가 k인 부분 문자열을 만들고, 해당 부분 문자열에서 모음의 개수를 세어야 합니다. 다음은 문제를 해결하는 알고리즘입니다:
class Solution {
public int maxVowels(String s, int k) {
int maxVowelCnt = 0;
int vowelCnt = 0;
for(int i = 0; i < s.length(); i++){
char chr = s.charAt(i);
vowelCnt += getVowel(chr);
if(i + 1 > k){
vowelCnt -= getVowel(s.charAt(i - k));
}
maxVowelCnt = Math.max(maxVowelCnt, vowelCnt);
}
return maxVowelCnt;
}
public int getVowel(char c){
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') ? 1 : 0;
}
}
1493. Longest Subarray of 1's After Deleting One Element (0) | 2023.11.06 |
---|---|
1004. Max Consecutive Ones III (0) | 2023.11.06 |
643. Maximum Average Subarray I (0) | 2023.11.02 |
1679. Max Number of K-Sum Pairs (0) | 2023.11.02 |
11. Container With Most Water (0) | 2023.11.02 |