思路

滑动窗口

代码

  1. var maxVowels = function(s, k) {
  2. // 元音字母集
  3. let keys = new Set(['a', 'e', 'i', 'o', 'u'])
  4. let count = 0;
  5. let left = 0, right = 0, winLen = 0;
  6. while(right <= s.length) {
  7. let cur = s[right]
  8. // 窗口扩大
  9. if (keys.has(cur)) {
  10. winLen ++;
  11. }
  12. // 窗口缩小
  13. if (right - left >= k) {
  14. if (keys.has(s[left])) {
  15. winLen --;
  16. }
  17. left ++;
  18. }
  19. count = Math.max(count, winLen);
  20. // 找到最多k个,直接退出
  21. if (count == k) break;
  22. right ++;
  23. }
  24. return count;
  25. };

复杂度

  • 时间复杂度 day35.[滑动窗口].1456. 定长子串中元音的最大数目 - 图1#card=math&code=O%28N%29)
  • 空间复杂度 day35.[滑动窗口].1456. 定长子串中元音的最大数目 - 图2#card=math&code=O%281%29)