+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2019-07(2)

2019-08(89)

2019-09(94)

2019-10(15)

2019-11(5)

[leetcode] 1456. Maximum Number of Vowels in a Substring of Given Length

发布于2020-11-09 16:50     阅读(661)     评论(0)     点赞(16)     收藏(2)


0

1

2

3

4

5

6

Description

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, 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.

Example 4:

Input: s = "rhythms", k = 4
Output: 0
Explanation: We can see that s doesn't have any vowel letters.

Example 5:

Input: s = "tryhard", k = 4
Output: 1

Constraints:

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.
  • 1 <= k <= s.length

分析

题目的意思是:这道题给定了一个字符串s,求s中长度为k的子串中包含元音字母的最大个数。这道题好像似曾相识,但是好像不记得解法了,看来要多复习。

思路很直接,用滑动窗口,遍历字符串,cnt记录滑动窗口里面的元音字母的数量,注意滑动窗口向右移动的时候,cnt要跟着变化就行了。然后维护最大值res.

代码

class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        n=len(s)
        res=0
        cnt=0
        for i in range(n):
            if(s[i] in 'aeiou'):
                cnt+=1
            if(i>=k and s[i-k] in 'aeiou'):
                cnt-=1
            res=max(res,cnt)
        return res

参考文献

1456. Maximum Number of Vowels in a Substring of Given Length

原文链接:https://blog.csdn.net/w5688414/article/details/109554620

0

1

2

3

4

5



所属网站分类: 技术文章 > 博客

作者:天青色等烟雨

链接: https://www.pythonheidong.com/blog/article/611478/77904f966d29c90d7236/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

16 0
收藏该文
已收藏

评论内容:(最多支持255个字符)