欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 1456. 定长子串中元音的最大数目(滑动窗口)

发布时间:2024/7/5 编程问答 53 豆豆
生活随笔 收集整理的这篇文章主要介绍了 LeetCode 1456. 定长子串中元音的最大数目(滑动窗口) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1. 题目

给你字符串 s 和整数 k 。

请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。

英文中的 元音字母 为(a, e, i, o, u)。

示例 1: 输入:s = "abciiidef", k = 3 输出:3 解释:子字符串 "iii" 包含 3 个元音字母。示例 2: 输入:s = "aeiou", k = 2 输出:2 解释:任意长度为 2 的子字符串都包含 2 个元音字母。示例 3: 输入:s = "leetcode", k = 3 输出:2 解释:"lee""eet""ode" 都包含 2 个元音字母。示例 4: 输入:s = "rhythms", k = 4 输出:0 解释:字符串 s 中不含任何元音字母。示例 5: 输入:s = "tryhard", k = 4 输出:1提示: 1 <= s.length <= 10^5 s 由小写英文字母组成 1 <= k <= s.length

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 先找到一个大小 k 的窗口
  • 然后向右滑动
class Solution { public:int maxVowels(string s, int k) {int count = 0, maxcount = 0, l = 0, r = 0;while(r < k){if(s[r]=='a'||s[r]=='e'||s[r]=='i'||s[r]=='o'||s[r]=='u')count++;r++;}maxcount = count;for( ; r < s.size(); ++l,++r){if(s[r]=='a'||s[r]=='e'||s[r]=='i'||s[r]=='o'||s[r]=='u')count++;if(s[l]=='a'||s[l]=='e'||s[l]=='i'||s[l]=='o'||s[l]=='u')count--;maxcount = max(maxcount, count);}return maxcount;} };

72 ms 9.9 MB

总结

以上是生活随笔为你收集整理的LeetCode 1456. 定长子串中元音的最大数目(滑动窗口)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。