Skip to content

3227. Vowels Game in a String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  bool doesAliceWin(string s) {
    // Let k be the number of vowels in s.
    // 1. If k == 0, Bob wins since Alice has no vowels to pick.
    // 2. If k % 2 == 1, Alice wins since Alice can pick the entire string.
    // 3. If k % 2 == 0, Alice wins since Alice can pick (k - 1) vowels,
    // then Bob will either pick a substring containing 0 vowels, resulting in
    // Alice picking the remaining entire string, or Bob couldn't pick at all
    // (the last vowel).
    return ranges::any_of(s, [this](char c) { return isVowel(c); });
  }

 private:
  bool isVowel(char c) {
    static constexpr string_view kVowels = "aeiou";
    return kVowels.find(c) != string_view::npos;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public boolean doesAliceWin(String s) {
    // Let k be the number of vowels in s.
    // 1. If k == 0, Bob wins since Alice has no vowels to pick.
    // 2. If k % 2 == 1, Alice wins since Alice can pick the entire string.
    // 3. If k % 2 == 0, Alice wins since Alice can pick (k - 1) vowels,
    // then Bob will either pick a substring containing 0 vowels, resulting in
    // Alice picking the remaining entire string, or Bob couldn't pick at all
    // (the last vowel).
    return s.chars().anyMatch(c -> isVowel((char) c));
  }

  private boolean isVowel(char c) {
    return "aeiou".indexOf(Character.toLowerCase(c)) != -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def doesAliceWin(self, s: str) -> bool:
    # Let k be the number of vowels in s.
    # 1. If k == 0, Bob wins since Alice has no vowels to pick.
    # 2. If k % 2 == 1, Alice wins since Alice can pick the entire string.
    # 3. If k % 2 == 0, Alice wins since Alice can pick (k - 1) vowels,
    # then Bob will either pick a substring containing 0 vowels, resulting in
    # Alice picking the remaining entire string, or Bob couldn't pick at all
    # (the last vowel).
    kVowels = 'aeiou'
    return any(c in kVowels for c in s)