Open azl397985856 opened 1 month ago
class Solution:
def maxVowels(self, s: str, k: int) -> int:
n = len(s)
if k > n:
return 0
def testv (arr):
count = 0
for char in arr:
if char == 'a' or char == 'e' or char =='i' or char == 'o' or char == 'u':
count += 1
return count
maxn = testv(s[:k])
current = testv(s[:k])
for i in range(k, n):
if s[i] == 'a' or s[i] == 'e' or s[i] =='i' or s[i] == 'o' or s[i] == 'u':
current += 1
if s[i - k ] == 'a' or s[i - k ] == 'e' or s[i - k ]=='i' or s[i - k ] == 'o' or s[i - k] == 'u':
current -= 1
maxn = max(maxn, current)
return maxn
Time: O(n)
Space: O(1)
class Solution:
def maxVowels(self, s: str, k: int) -> int:
res = 0
temp = 0
vowels = set(['a','e','i','o','u'])
for i in range(k):
res += s[i] in vowels
if res==k: return k
temp = res
for i in range(k,len(s)):
temp += (s[i] in vowels) - (s[i-k] in vowels)
res = max(temp,res)
if res ==k: return k
return res
class Solution:
def maxVowels(self, s: str, k: int) -> int:
maxVowelLength = 0
currentVowelCount = 0
vowels = set("aeiou")
# 计算第一个窗口的元音数量
for i in range(k):
if s[i] in vowels:
currentVowelCount += 1
maxVowelLength = currentVowelCount
# 移动窗口
for i in range(k, len(s)):
if s[i] in vowels:
currentVowelCount += 1
if s[i - k] in vowels:
currentVowelCount -= 1
maxVowelLength = max(maxVowelLength, currentVowelCount)
return maxVowelLength
先打卡
class Solution {
public int maxVowels(String s, int k) {
int maxVowels = 0;
int currentVowelCount = 0;
String vowels = "aeiou";
// Count vowels in the first window
for (int i = 0; i < k; i++) {
if (vowels.indexOf(s.charAt(i)) != -1) {
currentVowelCount++;
}
}
maxVowels = currentVowelCount;
// Slide the window
for (int i = k; i < s.length(); i++) {
if (vowels.indexOf(s.charAt(i - k)) != -1) {
currentVowelCount--; // Remove the vowel going out of the window
}
if (vowels.indexOf(s.charAt(i)) != -1) {
currentVowelCount++; // Add the new vowel coming into the window
}
maxVowels = Math.max(maxVowels, currentVowelCount);
}
return maxVowels;
}
}
func maxVowels(s string, k int) int {
vowels := map[byte]bool{
'a': true,
'e': true,
'i': true,
'o': true,
'u': true,
}
// 初始化窗口
count := 0
for i := 0; i < k; i++ {
if vowels[s[i]] {
count++
}
}
maxCount := count
for i := k; i < len(s); i++ {
if vowels[s[i-k]] {
count--
}
if vowels[s[i]] {
count++
}
if count > maxCount {
maxCount = count
}
}
return maxCount
}
复杂度分析
时间复杂度:O(N) 空间复杂度:O(1)
1456. 定长子串中元音的最大数目
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length
前置知识
暂无
题目描述