Skip to content

Commit 000c495

Browse files
committed
Add: Add 2025/9/12
1 parent 1a155c6 commit 000c495

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# 3227. Vowels Game in a String
2+
3+
Alice and Bob are playing a game on a string.
4+
5+
You are given a string `s`, Alice and Bob will take turns playing the following game where Alice starts first:
6+
7+
- On Alice's turn, she has to remove any non-empty substring from `s` that contains an odd number of vowels.
8+
- On Bob's turn, he has to remove any non-empty substring from `s` that contains an even number of vowels.
9+
10+
The first player who cannot make a move on their turn loses the game. We assume that both Alice and Bob play optimally.
11+
12+
Return `true` if Alice wins the game, and `false` otherwise.
13+
14+
The English vowels are: `a`, `e`, `i`, `o`, and `u`.
15+
16+
**Constraints:**
17+
18+
- `1 <= s.length <= 10^5`
19+
- `s` consists only of lowercase English letters.
20+
21+
## 基礎思路
22+
23+
這是一道博弈題目,但在觀察規則後可以發現,其實只需要判斷一個非常簡單的條件。
24+
25+
* Alice 與 Bob 輪流操作,Alice 只能移除「奇數個母音」的子字串,Bob 只能移除「偶數個母音」的子字串。
26+
* 如果輪到某個人無法操作,就輸了。
27+
* 題目還強調「兩人都採取最優策略」。
28+
29+
從規則出發,我們可以注意到一個重要性質:
30+
31+
* 任何**只要有至少一個母音**存在的字串,Alice 都可以移除單一母音,這是合法的奇數母音子字串。
32+
* Alice 是先手,只要她能做出第一次移除動作,就一定能掌握主動權並最終獲勝(她可以強迫 Bob 回應她的行為)。
33+
* 相反地,若字串中**完全沒有母音**,那 Alice 在第一回合就沒有合法行為,直接輸掉遊戲。
34+
35+
因此,我們只需要檢查字串中是否包含任一個母音,即可直接得出勝負。
36+
37+
## 解題步驟
38+
39+
### Step 1:遍歷字串,尋找任一母音是否存在
40+
41+
- 若發現任何一個母音(a/e/i/o/u),代表 Alice 可以先手出招,直接回傳 `true`
42+
- 否則整個字串不含母音,Alice 無法出手,回傳 `false`
43+
44+
```typescript
45+
for (let i = 0; i < s.length; i++) {
46+
if (s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' || s[i] === 'u') {
47+
// 若存在任一母音:Alice 可以在第一輪出手並獲勝
48+
return true;
49+
}
50+
}
51+
52+
// 若完全沒有母音:Alice 無法出手,直接輸掉遊戲
53+
return false;
54+
```
55+
56+
## 時間複雜度
57+
58+
- 最多只需掃描整個字串一次。
59+
- 每次判斷一個字元是否為母音屬於常數時間。
60+
- 總時間複雜度為 $O(n)$,其中 $n$ 為字串長度。
61+
62+
> $O(n)$
63+
64+
## 空間複雜度
65+
66+
- 除了迴圈中的索引變數外,未使用額外空間。
67+
- 沒有使用任何額外資料結構。
68+
- 總空間複雜度為 $O(1)$。
69+
70+
> $O(1)$
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
function doesAliceWin(s: string): boolean {
2+
for (let i = 0; i < s.length; i++) {
3+
if (s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' || s[i] === 'u') {
4+
// If at least one vowel exists: Alice can make the first move and win
5+
return true;
6+
}
7+
}
8+
9+
// No vowels found: Alice cannot make any valid move, so she loses
10+
return false;
11+
}

0 commit comments

Comments
 (0)