【力扣】定长子串中元音最大数目
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length
给你字符串 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 个元音字母。
看到这题想着控制y的范围防止越界,使用一个滑窗方法,再判断每个窗口的值满足题目要求的进行计数,暴力方法解决问题。没想到超时了。
1 class Solution: 2 def maxVowels(self, s: str, k: int) -> int: 3 q = ['a','e','i','o','u'] 4 c = [] 5 for y in range(len(s)-k+1): 6 b = 0 7 for j in s[y:y+k]: 8 if j in q : 9 b += 1 10 c.append(b) 11 return max(c)
附上其他同学的思路学习:
1 class Solution: 2 def maxVowels(self, s: str, k: int) -> int: 3 res = cur = 0 4 for i in range(len(s)): 5 if s[i] in 'aeiou': 6 cur += 1 7 if i >= k: 8 cur -= s[i-k] in 'aeiou' 9 res = max (res,cur) 10 return res 11 12 作者:HUST_PDE_YCX 13 链接:https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/solution/5417-ding-chang-zi-chuan-zhong-yuan-yin-de-zui-da-/ 14 来源:力扣(LeetCode)
$i$在向前遍历的过程中,当i比窗口值k大的时候,会回头检查窗口k=3走过的元素是否有丢掉的元音,有丢掉的元音-1。
k=3,
窗口内为abc,cur记录当前滑窗的为元音的元素个数,cur = 1
窗口内为bci,cur因为新加入一个原因元素+1,同时因为失去一个原音元素而-1,使用res记录暂时的最大值
沿着这个思路一直循环下去。
还有相同思路的其他使用指针的实现:
先将指针j向右移动k-1个位置(加上起始点构成长度为k的子串),计算元音字符数,然后将i,j同向移动实时更新最大元音数。
1 class Solution: 2 def maxVowels(self, s: str, k: int) -> int: 3 i, j = 0, 0 4 Hash = {'a':1, 'e':1, 'i':1, 'o':1, 'u':1} 5 res, tmp = 0, 0 6 while j < k: 7 if Hash.get(s[j], 0) > 0: 8 tmp += 1 9 j += 1 10 if j == k: 11 res = max(res, tmp) 12 13 while j < len(s): 14 if Hash.get(s[i], 0) > 0: 15 tmp -= 1 16 i += 1 17 if Hash.get(s[j], 0) > 0: 18 tmp += 1 19 j += 1 20 res = max(res, tmp) 21 22 return res 23 24 25 作者:yi-wen-statistics 26 链接:https://leetcode-cn.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/solution/shuang-zhi-zhen-by-yi-wen-statistics-13/ 27 来源:力扣(LeetCode)
浙公网安备 33010602011771号