[力扣] 算法 1456 (C#)

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

public class Solution {
    public int MaxVowels(string s, int k)
    {
        var cnts = new Counts();
        foreach (var ch in s.AsSpan(0, k)) cnts.Add(ch);
        var max = cnts.vowel;
        for(var i = k; max < k && i < s.Length; i++)
        {
            cnts.Remove(s[i - k]);
            cnts.Add(s[i]);
            if (cnts.vowel > max) max = cnts.vowel;
        }
        return max;
    }

    class Counts
    {
        public int vowel;
        HashSet<char> set = new HashSet<char>() { 'a', 'e', 'i', 'o', 'u' };
        public void Add(char c)
        {
            if (set.Contains(c))
                vowel++;
        }
        public void Remove(char c)
        {
            if (set.Contains(c))
                vowel--;
        }
    }
}

发表评论