Re: [閒聊] 每日LeetCode已回收
https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/description/
1456. Maximum Number of Vowels in a Substring of Given Length
給你一個包含小寫字母的字串 s ,返回大小為 k 的子字串中,最大母音字母數量。
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.
思路:
1.大小為 n 的子字串要求最大的xx很明顯是滑動窗口問題。
2.窗口每次加入一個字母,統計母音數量並更新最大母音數。
3.如果窗口大小超過 k 就移除最左邊的字母並更新窗口內的母音數量。
Java Code:
------------------------------------------------
class Solution {
public int maxVowels(String s, int k) {
int maxVowels = 0;
int curVowels = 0;
int l = 0, r = 0;
while (r < s.length()) {
if ((r - l + 1) > k) {
if (isVowels(s.charAt(l++))) {
curVowels--;
}
}
curVowels += isVowels(s.charAt(r++)) ? 1 : 0;
maxVowels = Math.max(maxVowels, curVowels);
}
return maxVowels;
}
private boolean isVowels(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}
------------------------------------------------
--
https://i.imgur.com/uiFto42.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1683307054.A.0AE.html
討論串 (同標題文章)
完整討論串 (本文為第 313 之 719 篇):