1 回答
TA贡献1811条经验 获得超6个赞
像这样的东西会快得多,它只是一次 O(1) 查找的线性传递:
def count_vowels(s, k):
vowels = set("aeiouAEIOU")
#count first k
t = sum(1 for i in s[:k] if i in vowels)
mx = t
for i in range(k, len(s)):
if s[i] in vowels:
t+=1
if s[i-k] in vowels:
t-=1
if t > mx:
mx = t
return mx
count_vowels("eirowpfmsnaquisaaaa",5)
下面是如何在 JavaScript 中实现这一点:
function count_vowels(s, k) {
const vowels = new Set(Array.from("aeiouAEIOU"));
let t = 0;
//count first k
for (let i = 0; i < k && i < s.length; i++) {
t += vowels.has(s[i]) ? 1 : 0;
}
let mx = t;
for (let i = k; i < s.length; i++) {
if (vowels.has(s[i])) {
t += 1
}
if (vowels.has(s[i - k])) {
t -= 1;
}
if (t > mx) {
mx = t;
}
}
return mx;
}
console.log(count_vowels("eirowpfmsnaquisaaaa", 5))
添加回答
举报