Input: s ="leetcoder"Output: trueExplanation:
Alice can win the game as follows:* Alice plays first, she can delete the underlined substring in`s = "_**leetco**_ der"` which contains 3 vowels. The resulting string is`s = "der"`.* Bob plays second, he can delete the underlined substring in`s = "_**d**_ er"` which contains 0 vowels. The resulting string is`s = "er"`.* Alice plays third, she can delete the whole string `s = "**_er_** "` which contains 1 vowel.* Bob plays fourth, since the string is empty, there is no valid play for Bob. So Alice wins the game.
The key is to count the number of vowels in the string. If the number of vowels is odd, Alice can always win by removing the whole string (which is a valid move for her). If the number of vowels is even and greater than zero, Bob can always win by removing the whole string on his turn. If there are no vowels, Alice cannot make a move and loses.
Count the number of vowels in the string. If the count is odd, Alice wins. If the count is even and greater than zero, Bob wins. If there are no vowels, Alice loses immediately.
classSolution {
public:bool aliceWins(string s) {
int cnt =0;
for (char c : s) {
if (c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u') cnt++;
}
return cnt %2==1;
}
};
classSolution {
publicbooleanaliceWins(String s) {
int cnt = 0;
for (char c : s.toCharArray()) {
if (c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u') cnt++;
}
return cnt % 2 == 1;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funaliceWins(s: String): Boolean {
var cnt = 0for (c in s) {
if (c =='a'|| c =='e'|| c =='i'|| c =='o'|| c =='u') cnt++ }
return cnt % 2==1 }
}
1
2
3
4
5
classSolution:
defaliceWins(self, s: str) -> bool:
vowels = set('aeiou')
cnt = sum(1for c in s if c in vowels)
return cnt %2==1