Open azl397985856 opened 3 years ago
class Solution {
public int maxVowels(String s, int k) {
//固定窗口大小
if(s.length() <= 0 || s.length()<k){
return 0;
}
char[] c = s.toCharArray();
int ans = 0;
// 首先检查第一个窗口,看看里面有多少个
for (int i = 0; i < k; ++i)
if (isVowel(c[i])) {
ans++;
}
// 然后从第一个位置开始滑动窗口,直到最后一个
int window = ans;
for (int left = 0, right = k; right < c.length; left++, right++) {
if (isVowel(c[left])) window--;
if (isVowel(c[right])) window++;
ans = Math.max(ans, window);
}
return ans;
}
public boolean isVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ? true : false;
}
}
先开始有个错误思路, 就是想用slicing window, 但是实际上的复杂度是 O( (n-k)*k), 极端情况下就是 n^2 了. 后来用pointer 解决. 边界题很简单, 无非第一就是想inital + last 的情况, 第二就是穷举集中combination. 其实并不难
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowel = {'a','e', 'i', 'o', 'u'}
res = 0
'''
for i in range(len(s)-k+1):
count = 0
#print(s[i:i+k])
for j in s[i:i+k]:
if j in vowel:
count+=1
res = max(res, count)
return res
'''
res = count = 0
for j in s[0:k]:
if j in vowel:
count += 1
res = count
for i in range(k,len(s)):
r = l = 0
if s[i] in vowel:
r = 1
if s[i-k] in vowel:
l = 1
count = count - l +r
res = max(count, res)
return res
https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length
题干理解:
class Solution: #132ms
def maxVowels(self, s: str, k: int) -> int:
res = 0
temp = 0
vowels = set(['a','e','i','o','u'])
for i in range(k):
if s[i] in vowels:
res += 1
temp = res
for i in range(k,len(s)): #右边窗口进的字符是否元音
if s[i] in vowels:
temp += 1
if s[i-k] in vowels:#左边窗口出的字符是否元音
temp -= 1
res = max(temp,res)
return res
复杂度分析:
思路
滑动窗口,往右滑动匹配到正确字符则添加 左边边界碰到正确字符对应count-1.每次统计最大count
代码
class Solution {
public int maxVowels(String s, int k) {
int left = 0,right = 0;
int count = 0;
char[] chars = s.toCharArray();
int tempCount = 0;
while (right < s.length()) {
if (chars[right] == 'a' || chars[right] == 'e' || chars[right] == 'i' || chars[right] == 'o' || chars[right] == 'u'){
tempCount++;
}
right++;
if(right > k) {
if (chars[left] == 'a' || chars[left] == 'e' || chars[left] == 'i' || chars[left] == 'o' || chars[left] == 'u') {
tempCount--;
}
left++;
}
count = Math.max(count,tempCount);
}
return count;
}
}
复杂度
时间复杂度:O(N)
空间复杂度:O(1)
滑动窗口,遍历一次
public int maxVowels(String s, int k) {
Queue<Integer> queue = new LinkedList<>();
Map<Character, Integer>map = new HashMap<>();
map.put('a',1);
map.put('e',1);
map.put('i',1);
map.put('o',1);
map.put('u',1);
int max = 0;
for (int i = 0; i < s.length(); i++) {
int l =i-k;
int r =k-1;
if(i>r&&queue.size()!=0&&queue.peek()==l){
queue.poll();
}
Character si = s.charAt(i);
if(map.containsKey(si)){
queue.add(i);
max = Math.max(max,queue.size());
if(max==k){
return k;
}
}
}
return max;
}
var maxVowels = function (s, k) {
let set = new Set(["a", "e", "i", "o", "u"]);
let count = 0;
for (let i = 0; i < k; i++) {
if (set.has(s[i])) count++;
}
let ans = count;
for (let i = k; i < s.length; i++) {
if (set.has(s[i])) count++;
if (set.has(s[i - k])) count--;
ans = Math.max(count, ans);
}
return ans;
};
思路:滑动窗口+哈希表
class Solution {
public int maxVowels(String s, int k) {
char[] c = s.toCharArray();
Set<Character> set = new HashSet<>();
// 元音字符表
set.add('a');set.add('e');set.add('i');set.add('o');set.add('u');
int ans = 0;
// 首先检查第一个窗口,看看里面有多少个
for (int i = 0; i < k; ++i)
if (set.contains(c[i])) {
ans++;
}
// 然后从第一个位置开始滑动窗口,直到最后一个
int window = ans;
for (int left = 0, right = k; right < c.length; ++left, ++right) {
if (set.contains(c[left])) window--;
if (set.contains(c[right])) window++;
ans = Math.max(ans, window);
}
return ans;
}
}
时间复杂度:O(N) 空间复杂度:O(N)
滑动窗口方法: 保持一个k大小的窗口, 和一个元音计数器 逐渐移动. 当窗口末尾的字符是元音, 计数器-1 当窗口右侧的字符是元音, 计数器+1
def maxVowels(self, s: str, k: int) -> int:
vowels = ['a','e','i','o','u']
count= 0
for i in range(k):
if s[i] in vowels:
count+=1
p1,p2,temp = 0,k-1,count
while(p2<len(s)-1):
if s[p1] in vowels:
temp-=1
if s[p2+1] in vowels:
temp+=1
count = max(temp,count)
p1+=1
p2+=1
return count
K 长 滑动窗口从左往右滑,右进一个字符如果是元音则 K 长内字符子串 最长元音+1, 滑动前 最左字符如果是元音则 K 长内字符子串 最长元音-1; 每次滑动,标记子串最大元音个数为 max_in_k, 每次滑动跟 全局 最大值 max 做 比较,提取较大值重新赋值给 全局 max;
class Solution {
bool isVowel(char ch) {
return ch == 'a' ||
ch == 'o' ||
ch == 'e' ||
ch == 'i' ||
ch == 'u';
}
int maxVolInKSequence(String s, int k) {
int i = 0;
int maxVols = 0;
int k = 0;
while (i < s.size()) {
if (isVowel(s.at[i])) {
++k;
}
if (i >= k && isVowel(s[i - k]))
--k;
maxVols = max(maxVols, k);
++i;
}
}
return maxVols;
}
思路: 滑动窗口 1、自己的思路开始直接循窗口然后判断是否存在.复杂度过高,在没想到啥好方法的时候. 在看了题解后发现可以更好优化空间复杂度O(1) 下面直接写出自己实现的代码 1、map保存需要找到的字符,判断是否存在 2、分步骤分析滑动窗口的移动和下标 first(窗口开始位置0),last(窗口结束位置Len) 3、保存记录初始化窗口中出现的最大次数
var maxVowels = function(arr, target) {
let map = new Map();
map.set('a', 0)
map.set('e', 0)
map.set('i', 0)
map.set('o', 0)
map.set('u', 0)
let resNum = 0
for (let i = 0; i < target; i++) {
if (map.has(arr[i])) {
resNum++
}
}
let temp = resNum
for (let i = 0, k = target; k < arr.length; i++, k++) {
console.log(arr[i], arr[k], map.has(arr[i]), map.has(arr[k]))
if (map.has(arr[k])) {
temp++
}
if (map.has(arr[i])) {
temp--
}
resNum = Math.max(resNum, temp)
}
return resNum
};
时间复杂度:O(n) 空间复杂度:O(1)
滑动窗口,先计算前k个字符中的元音数,形成初步窗口。之后每次right和left各进一步,并更改滑动窗口的元音值。取最大元音值个数即可。
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vos="aeiou"
left=0
m=len(s)
cnt=0
for i in range(k):
if s[i] in vos:
cnt+=1
res=cnt
for right in range(k,m):
if s[right] in vos:
cnt+=1
if s[left] in vos:
cnt-=1
left+=1
res=max(res,cnt)
return res
时间复杂度:O(n) 遍历一遍字符串
空间复杂度:O(1)
class Solution {
public int maxVowels(String s, int k) {
int max = 0;
// 初始化窗口
for(int i = 0; i< k; i++) {
if(isVowels(s.charAt(i))) {
max ++;
}
}
int window = max;
// 更新窗口
for( int i = k ; i < s.length(); i++) {
if(isVowels(s.charAt(i))) {
window ++;
}
if(isVowels(s.charAt(i - k))) {
window --;
}
max = Math.max(max, window);
}
return max;
}
private boolean isVowels(char c) {
return c == 'a' || c =='e' || c == 'i'|| c == 'o'|| c == 'u' ;
}
}
LC 1456. Maximum Number of Vowels in a Substring of Given Length
Ideas -slide window
comment 350 ms, faster than 12.87%
python代码
class Solution:
def maxVowels(self, s: str, k: int) -> int:
length = len(s)
res = 0
tmp = 0
vowel_letters = ['a','e','i','o','u']
for i in range(k):
res += s[i] in vowel_letters
if res == k:
return k
tmp = res
for i in range(k,length):
tmp += (s[i] in vowel_letters) - (s[i-k] in vowel_letters)
res = max(tmp,res)
if res == k:
return k
return res
维持一个长度为k的,每次窗口移动进行元音字母的个数的加减,然后每次和max比较
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels_set = {"a", "e", "i", "o", "u"}
start = 0
vowel_count = max_vowel_count = 0
for i in range(len(s)):
if s[i] in vowels_set:
vowel_count += 1
while i - start == k:
if s[start] in vowels_set:
vowel_count -= 1
start += 1
max_vowel_count = max(max_vowel_count, vowel_count)
return max_vowel_count
Time O(n)
Space O(1)
固定大小的滑动窗口,如果超出窗口的最后一个字母是元音则在count中减去它,否则检查当前的字母是否是元并update cnt和ans。
int maxVowels(string s, int k) {
unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u'};
int cnt = 0;
int ans = 0;
for (int i = 0; i < s.size(); ++i) {
if (i >= k) {
cnt -= vowels.count(s[i - k]); // reduce 1 if the out-of-bound char is a vowel
}
cnt += vowels.count(s[i]);
ans = max(ans, cnt);
}
return ans;
}
};
定长滑动窗口
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
var maxVowels = function(s, k) {
let l = 0, r = 0;
let ans = -Infinity, count = 0
const set = new Set(['a','e','i','o','u'])
while (r < s.length) {
if (set.has(s[r])) count ++
// 滑动窗口,当满足当前窗口大于 k 时 缩小左边界
if ((r - l) >= k) {
set.has(s[l]) && count--;
l ++
}
ans = Math.max(ans, count)
r ++
}
return ans
};
时间复杂度 O(s)
空间复杂度 O(1)
Go Code:
func maxVowels(s string, k int) int {
var win [26]int
var res int
for i := 0; i < len(s); i++ {
win[s[i]-97]++
if i < k-1 {
continue
}
res = max(res, win[0]+win[4]+win[8]+win[14]+win[20])
win[s[i-(k-1)]-97]--
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
复杂度分析
令 n 为数组长度。
Problem Link
Ideas
Complexity: hash table and bucket
Code
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = ['a','e','i','o','u']
print (s)
maxcount = 0
for i in range(k):
if s[i] in vowels:
maxcount += 1
curcount = maxcount
for i in range(k, len(s)):
curcount = curcount - (s[i-k] in vowels) + (s[i] in vowels)
maxcount = max(maxcount, curcount)
if maxcount == k: return k
return maxcount
https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/
Hard
Medium
hash table + slide window
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = set(["a", "e", "i", "o", "u"])
t_d = defaultdict(int)
for i in range(k):
if s[i] in vowels:
t_d[s[i]] += 1
result = sum(t_d.values())
for j in range(k, len(s)):
if s[j-k] in t_d:
t_d[s[j-k]] -= 1
if s[j] in vowels:
t_d[s[j]] += 1
result = max(result, sum(t_d.values()))
return result
时间复杂度: O(k*n) 空间复杂度:O(k)
var maxVowels = function(s, k) {
let currWindow=0,len=s.length;vowels=['a','e','i','o','u','A','E','I','O','U']
for(let i=0;i<k&&i<len;i++)
if(vowels.includes(s.charAt(i)))
currWindow++
let maxVowels = currWindow
for(let i=k;i<len;i++)
{
if(vowels.includes(s.charAt(i)))
currWindow++
if(vowels.includes(s.charAt(i-k)))
currWindow--
maxVowels=Math.max(maxVowels,currWindow)
}
return maxVowels
};
/*Time complexity: O(n)
Space complexity: O(1)
*/
var maxVowels = function(s, k) {
let ans = 0;
let count = 0;
let right = 0;
for (let i = 0; i < s.length; i++) {
if (isVowel(s[i])) {
count++;
}
if (i >= k && isVowel(s[i - k])) {
count--;
}
ans = Math.max(ans, count);
}
return ans;
};
var isVowel = function (char) {
if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
return true;
}
return false;
}
滑动窗口。窗口大小固定为k。先检查最开始的k个字符,算出元音字符的数目。然后每次向后移动一位,检查刚出窗口和刚入窗口的两个字符,算出更新的元音数目。每次更新最大值,最后返回结果。
class Solution {
public int maxVowels(String s, int k) {
int count = 0;
for (int i = 0; i < k; i++) {
if (isVowel(s.charAt(i))) {
count++;
}
}
int max = count;
for (int j = 1; j <= s.length() - k; j++) {
if (isVowel(s.charAt(j - 1))) {
count--;
}
if (isVowel(s.charAt(j + k - 1))) {
count++;
}
max = Math.max(max, count);
}
return max;
}
private boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}
复杂度分析
【思路】左右指针,如果左边不是就--,右边是元音就++ 【复杂度】O(N)
public int maxVowels(String s, int k) {
int count = 0;
int ans = 0;
for(int i = 0 ; i < k ;i++){
char temp = s.charAt(i);
if(temp=='a'||temp=='e'||temp=='i'||temp=='o'||temp=='u'){
count ++;
}
}
ans = count;
for(int i = 1; i<s.length()-k+1;i++){
char left = s.charAt(i-1);
char right = s.charAt(i+k-1);
if(left=='a'||left=='e'||left=='i'||left=='o'||left=='u'){
count --;
}
if(right=='a'||right=='e'||right=='i'||right=='o'||right=='u'){
count++;
}
ans = Math.max(ans,count);
}
return ans;
}
var maxVowels = function (s, k) {
const dict = new Set(["a", "e", "i", "o", "u"]);
let ret = 0;
for (let i = 0; i < k; i++) {
if (dict.has(s[i])) ret++;
}
let temp = ret;
for (let i = k, j = 0; i < s.length; i++, j++) {
if (dict.has(s[i])) temp++;
if (dict.has(s[j])) temp--;
ret = Math.max(temp, ret);
}
return ret;
};
时间复杂度:O(n),n 为字串长度
空间复杂度:O(1)
Simple fix window problem. First check the first k substring's count of vowel. Then start to slide window (right ++, left ++) at the same time, check the updates of vowel count. Then compare with first k substring count and choose the maximum to update result.
class Solution:
def maxVowels(self, s: str, k: int) -> int:
# moving window
vowelSet = {"a", "e", "i", "o", "u"}
ans = 0
cnt = 0
for i in range(k):
if s[i] in vowelSet:
cnt += 1
ans = cnt
for i in range(k, len(s)):
ins = s[i]
outs = s[i - k]
if outs in vowelSet:
cnt -= 1
if ins in vowelSet:
cnt += 1
ans = max(ans, cnt)
return ans
-First adds all the vowel into a set. -Start off with a pointer, scan through the string. -If the current pointer points to a vowel, counter++, if pointer >= window k, examine if the letter exits the window is a vowel or not. -Have a maxCounter and counter for current window, compare current counter and maxCounter, returns the max.
class Solution {
public int maxVowels(String s, int k) {
Set<Character> vowelSet = new HashSet<>();
String vowel = "aeiou";
for (int i = 0; i < vowel.length(); i++) {
vowelSet.add(vowel.charAt(i));
}
int count = 0;
int maxCnt = 0;
for (int i = 0; i < s.length(); i++) {
if (vowelSet.contains(s.charAt(i))) {
count++;
}
if (i >= k && vowelSet.contains(s.charAt(i - k))) {
count--;
}
maxCnt = Math.max(maxCnt, count);
}
return maxCnt;
}
}
Time/Space complexity: O(N)/O(1)
class Solution {
public:
int maxVowels(string s, int k) {
unordered_map<char, int> m;
int res = INT_MIN;
int vowelSum = 0;
int left = 0;
for(int i = 0 ; i < s.size();i++) {
if(isVowel(s[i]))
vowelSum++;
if(i - left + 1 > k ) {
if(isVowel(s[left]))
vowelSum--;
left++;
}
res = max(res, vowelSum);
}
return res;
}
bool isVowel(char ch) {
if(ch == 'a' || ch =='e' || ch=='i' || ch =='o' || ch =='u')
return true;
return false;
}
};
套滑动窗口模板,一次遍历解决
class Solution {
public int maxVowels(String s, int k) {
int count = 0;
List<Character> vowerList = new ArrayList<Character>(Arrays.asList(new Character[]{'a','e','i','o','u'}));
for(int i=0;i<k;i++){
char c = s.charAt(i);
if(vowerList.contains(c)){
count++;
}
}
int max = count;
for(int i=0;i<s.length()-k;i++){
char startC = s.charAt(i);
if(vowerList.contains(startC)){
count--;
}
char endC = s.charAt(i+k);
if(vowerList.contains(endC)){
count++;
}
if(count>max){
max = count;
}
}
return max;
}
}
思路
复杂度
代码(C++)
class Solution {
public:
int maxVowels(string s, int k) {
int res = 0;
set<char> st = {'a','e','i','o','u'};
int l = 0, num = 0;
for (int i = 0; i < s.length(); ++i) {
while (i - l >= k) {
if (st.count(s[l]))
--num;
++l;
}
if (i - l < k && st.count(s[i]))
++num;
res = max(res, num);
}
return res;
}
};
滑动窗口
var maxVowels = function (s, k) {
const dict = new Set(["a", "e", "i", "o", "u"]);
let ret = 0;
for (let i = 0; i < k; i++) {
if (dict.has(s[i])) ret++;
}
let temp = ret;
for (let i = k, j = 0; i < s.length; i++, j++) {
if (dict.has(s[i])) temp++;
if (dict.has(s[j])) temp--;
ret = Math.max(temp, ret);
}
return ret;
};
复杂度
const maxVowels = function(s, k) {
const vowels = new Set(["a", "e", "i", "o", "u"]);
let maxCount = 0;
let currCount = 0;
let l = 0;
let i = 0;
while (i < k) {
if (vowels.has(s[i++])) maxCount = Math.max(maxCount, ++currCount);
}
while (i < s.length) {
if (vowels.has(s[l++])) currCount--;
if (vowels.has(s[i++])) maxCount = Math.max(maxCount, ++currCount);
}
return maxCount;
};
时间复杂度:O(n) 空间复杂度:O(1)
-First adds all the vowel into a set. -Start off with a pointer, scan through the string. -If the current pointer points to a vowel, counter++, if pointer >= window k, examine if the letter exits the window is a vowel or not. -Have a maxCounter and counter for current window, compare current counter and maxCounter, returns the max.
class Solution { public int maxVowels(String s, int k) {
Set<Character> vowelSet = new HashSet<>();
String vowel = "aeiou";
for (int i = 0; i < vowel.length(); i++) {
vowelSet.add(vowel.charAt(i));
}
int count = 0;
int maxCnt = 0;
for (int i = 0; i < s.length(); i++) {
if (vowelSet.contains(s.charAt(i))) {
count++;
}
if (i >= k && vowelSet.contains(s.charAt(i - k))) {
count--;
}
maxCnt = Math.max(maxCnt, count);
}
return maxCnt;
}
} Time/Space complexity: O(N)/O(1)
固定长度的滑动窗口。
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowel = 'aeiou'
start,end = 0,k-1
curr = 0
for i in range(min(k,len(s))):
if s[i] in vowel:
curr +=1
ans = curr
while end<len(s)-1:
end+=1
if s[end] in vowel:
curr+=1
if s[start] in vowel:
curr-=1
start+=1
ans = max(ans,curr)
return ans
复杂度分析
滑动窗口
class Solution {
public int maxVowels(String s, int k) {
int res = 0;
int max = 0;
int left = 0;
int right = k ;
LinkedList<Character> list = new LinkedList<Character>();
for(; left < k; left++){
char c = s.charAt(left);
list.addLast(c);
if(c == 'a' || c =='e'|| c =='i'|| c =='o'|| c =='u'){
max++;
}
}
res = max;
while(right < s.length()){
char temp = s.charAt(right);
list.addLast(temp);
if(temp == 'a' || temp =='e'|| temp =='i'|| temp =='o'|| temp =='u'){
max++;
}
char lead = list.removeFirst();
if(lead == 'a' || lead =='e'|| lead =='i'|| lead =='o'|| lead =='u'){
max--;
}
System.out.print(lead + " ");
res = Math.max(max,res);
right++;
}
return res;
}
}
时间复杂度:O(n) n字符串长度 空间复杂度:O(k) k 给定子字符串长度
大小为k的滑动窗口,每右移一格,检查刚出窗口元素和刚进窗口的元素是否是元音并更新count。
class Solution {
public int maxVowels(String s, int k) {
int n = s.length();
int count = 0;
for(int i = 0; i < k; i++){
if (isVowel(s.charAt(i))){
count++;
}
}
int res = count;
for (int j = 1; j < n - k + 1; j++){
if (isVowel(s.charAt(j - 1))) {
count--;
}
if (isVowel(s.charAt(j + k - 1))){
count++;
}
res = Math.max(count,res);
}
return res;
}
private boolean isVowel(char c){
if (c == 'a' || c == 'e'|| c == 'i' || c == 'o' || c == 'u'){
return true;
}
return false;
}
}
int maxVowels(string s, int k) {
set<char> vowels{'a', 'e', 'i', 'o', 'u'};
int l = 0, r = k - 1;
int maxvowels = 0;
int count = 0;
for (; r < s.length(); r++) {
if(r == k - 1)
{
for (int j = l; j <= r; j++) {
if (vowels.find(s[j]) != vowels.end())
count++;
}
}
else
{
if(vowels.count(s[l - 1]))
count--;
if(vowels.count(s[r]))
count++;
}
if (maxvowels < count)
maxvowels = count;
l++;
}
return maxvowels;
}
看的题解 1、map保存需要的元音字符表 2、检查第一个窗口,看看里面有多少个 3、然后从第一个位置开始滑动窗口,直到最后一个
class Solution {
public int maxVowels(String s, int k) {
char[] c = s.toCharArray();
Set<Character> set = new HashSet<>();
set.add('a');
set.add('e');
set.add('i');
set.add('o');
set.add('u');
int ans = 0;
for (int i = 0; i < k; i++)
if (set.contains(c[i])) {
ans++;
}
int count = ans;
for (int left = 0, right = k; right < c.length; left++, right++) {
if (set.contains(c[left])) {
count--;
}
if (set.contains(c[right])) {
count++;
}
ans = Math.max(ans, count);
}
return ans;
}
}
因为k是定长的,思路就相对简单,只要用一个k大小的滑窗从头往后扫,扫到元音cnt+1,元音出窗就cnt-1
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = {"a", "e", "i", "o", "u"}
l = 0
if len(s) < k:
return 0
max_cnt, cnt = 0, 0
for r in range(len(s)):
if r <= k - 1:
if s[r] in vowels:
cnt += 1
max_cnt = max(max_cnt, cnt)
else:
if s[r] in vowels:
cnt += 1
if s[l] in vowels:
cnt -= 1
l += 1
max_cnt = max(max_cnt, cnt)
return max_cnt
固定长度的滑动窗口,在窗口右端判断是否++,左端判断是否--
class Solution {
public:
bool isVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
int maxVowels(string s, int k) {
int n = s.size();
int vowel_count = 0;
for (int i = 0; i < k; ++i) {
if (isVowel(s[i])) {
++vowel_count;
}
}
int ans = vowel_count;
for (int i = k; i < n; ++i) {
if (isVowel(s[i - k])) {
--vowel_count;
}
if (isVowel(s[i])) {
++vowel_count;
ans = max(ans, vowel_count);
}
}
return ans;
}
};
时间 O(n)
空间 O(1)
固定窗口长度,从头往后扫,检查出窗和入窗的字母。
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels=['a','e','i','o','u']
count=0
max_count=0
left=0
for i in range(len(s)):
if s[i] in vowels:
count+=1
if i >=k-1:
max_count=max(max_count,count)
if s[left] in vowels:
count-=1
left+=1
return max_count
Time: O(n)
Space: O(1)
滑动窗口
Java Code:
class Solution {
public static boolean check (char ch) {
return (ch == 'a' || ch == 'e' || ch == 'i' | ch == 'o' || ch == 'u');
}
public int maxVowels (String s, int k) {
int max = 0, n = s.length();
int count = 0;
for (int i = 0; i < k; i++) {
if (check(s.charAt(i))) count++;
}
max = count;
for (int i = k; i < n; i++) {
if (check(s.charAt(i - k))) count--;
if (check(s.charAt(i))) count++;
max = Math.max(max, count);
}
return max;
}
}
复杂度分析
令 n 为数组长度。
C++ Code:
class Solution {
public:
int maxVowels(string s, int k) {
int res = 0;
int slow = 0, fast = 0;
int temp = 0;
for (; fast < s.length(); ++fast) {
if (isyuan(s[fast])) {
++temp;
}
if (fast - slow >= k) {
temp -= isyuan(s[slow]);
++slow;
}
res = max(res, temp);
}
return res;
}
bool isyuan(char& c) {
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
};
令 n 为数组长度。
1456. 定长子串中元音的最大数目
https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/)
先遍历前k个字符,记录元音字母个数cnt,并初始化返回值res = cnt 继续遍历索引k开始的字符,如果索引i - k处(也就是滑动窗口外)的字符也是元音字符,cnt - 1 如果当前字符为元音字符,cnt + 1,并且更新res
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = {'a', 'e', 'i', 'o', 'u'}
cnt = 0
for i in range(k):
if s[i] in vowels:
cnt += 1
res = cnt
for i in range(k, len(s)):
if s[i - k] in vowels:
cnt -= 1
if s[i] in vowels:
cnt += 1
res = max(res, cnt)
return res
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
const maxVowels = function(s, k) {
const vowels = new Set('aeiou');
let maxCount = 0;
let count = 0;
let left = 0;
for (let right = 0; right < s.length; ++right) {
if (vowels.has(s[right])) count += 1;
if (right < k - 1) continue; // not reached at least k size yet
if (right >= k && vowels.has(s[left++])) count -= 1;
maxCount = Math.max(maxCount, count);
if (maxCount === k) break; // found max possible
}
return maxCount;
};
https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/
class Solution {
public int maxVowels(String s, int k) {
// Set<Character> set = new HashSet<>(){{add('a'); add('e'); add('i'); add('o'); add('u');}};
Set<Character> set = Set.of('a', 'e', 'i', 'o', 'u');
int count = 0;
for(int i = 0; i < k; i++){
if(set.contains(s.charAt(i))){
count++;
}
}
int max = count;
int j = k;
while(j < s.length()){
if(set.contains(s.charAt(j))){
count++;
}
if(set.contains(s.charAt(j - k))){
count--;
}
j++;
max = Math.max(max, count);
}
return max;
}
}
var maxVowels = function (s, k) {
const dist=new Set(['a','e','i','o','u'])
let count=0;
let l=r=0;
while(r<k){
if(dist.has(s[r])){
count++
}
r++
}
let max = count
while(r<s.length){
if(dist.has(s[l])){
count--
}
if(dist.has(s[r])){
count++
}
l++;
r++
max = Math.max(max, count)
}
return max;
};
时间复杂度O(n),空间复杂度O(n)
class Solution {
public int maxVowels(String s, int k) {
HashSet<Character> set = new HashSet();
set.add('a');
set.add('e');
set.add('i');
set.add('o');
set.add('u');
int res = 0, count = 0;
for (int i = 0; i < k; i++) {
if (set.contains(s.charAt(i))) {
res++;
}
}
count = res;
int left = 1, right = left + k - 1;
while (right < s.length()) {
if (set.contains(s.charAt(right))) {
count++;
}
if (set.contains(s.charAt(left - 1))) {
count--;
}
//System.out.println(count);
res = Math.max(res, count);
right++;
left++;
}
return res;
}
}
var maxVowels = function(s, k) {
if(!s){
return 0
}
var len = s.length;
var p1 = 0;
var p2 = k-1;
var originLen = 0;
var yuanStr = 'aeiouAEIOU'
for(var i=0;i<k;i++){
if(yuanStr.indexOf(s[i])>=0){
originLen+=1
}
}
var maxLen = originLen
while(p2<len-1){
if(yuanStr.indexOf(s[p1])>=0){
originLen-=1
}
p2+=1;
p1+=1;
if(yuanStr.indexOf(s[p2])>=0){
originLen+=1
}
maxLen = Math.max(maxLen,originLen)
}
return maxLen;
};
滑动窗口,check弹出窗口的字母是否为元音字母,如是-1,否则pass,check加入窗口的字母,如是元音字母+1, 否则pass
使用语言:Python3
class Solution:
def maxVowels(self, s: str, k: int) -> int:
v = ['a', 'e', 'i', 'o', 'u']
max_num = 0
cur_num = 0
l = 0
r = l + k - 1
for i in range (k):
if s[i] in v:
cur_num += 1
max_num = max(max_num, cur_num)
while r < len(s) - 1:
if s[l] in v:
cur_num -= 1
if s[r+1] in v:
cur_num += 1
max_num = max(max_num, cur_num)
l += 1
r += 1
return max_num
复杂度分析 时间复杂度:O(n) 空间复杂度:O(1)
class Solution:
def maxVowels(self, s: str, k: int) -> int:
cnt, max_len = 0, 0
# check if character is vowel, return boolean
def is_vowels(char):
return True if char in "aeiou" else False
# first fit window size
for char in s[:k]:
if is_vowels(char):
cnt += 1
max_len = cnt
# keep scanning string
for i in range(k, len(s)):
if is_vowels(s[i]):
cnt += 1
if is_vowels(s[i-k]):
cnt -= 1
max_len = max(max_len, cnt)
return max_len
1456. 定长子串中元音的最大数目
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length
前置知识
暂无
题目描述