Blog.

定长子串中元音的最大数目

Cover Image for 定长子串中元音的最大数目
Bernie
Bernie

1456. 定长子串中元音的最大数目

leetcode 链接

思路:

滑动窗口 先计算前 k 个字符中的元音个数, 在遍历 k 后面的字符,如果 nj 是元音,则结果+1, 如果 n[j - k]是元音,则结果-1, 最后判断结果是否大于最大值,如果大于则更新最大值,最后返回最大值即可。

typescript 解法

function maxVowels(s: string, k: number): number {
  let max: number = 0;
  let count: number = 0;
  const length: number = s.length;
  for (let i = 0; i < k; i++) {
    if (isVowel(s[i])) {
      count++;
    }
  }
  max = count;
  for (let j = k; j < length; j++) {
    if (isVowel(s[j])) {
      count++;
    }
    if (isVowel(s[j - k])) {
      count--;
    }
    if (count > max) {
      max = count;
      if (max === k) {
        return max;
      }
    }
  }
  return max;
}
function isVowel(s: string): boolean {
  return "aeiou".includes(s);
}

go 解法

func maxVowels(s string, k int) int {
    length := len(s)
    max := 0
    count := 0
    for i := 0; i < k; i ++ {
        if isVowel(string(s[i])) {
            count ++
        }
    }
    max = count
    for j := k; j < length; j ++ {
        if isVowel(string(s[j])) {
            count ++
        }
        if isVowel(string(s[j - k])) {
            count --
        }
        if count > max {
            max = count
            if max == k {
                return max
            }
        }

    }
    return max
}
func isVowel(s string) bool {
    return s == "a" || s == "e" || s == "i" || s == "o" || s == "u"
}