Skip to content

Commit 23129b1

Browse files
committed
Add solution #294
1 parent 218a9b7 commit 23129b1

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,7 @@
282282
291|[Word Pattern II](./solutions/0291-word-pattern-ii.js)|Medium|
283283
292|[Nim Game](./solutions/0292-nim-game.js)|Easy|
284284
293|[Flip Game](./solutions/0293-flip-game.js)|Easy|
285+
294|[Flip Game II](./solutions/0294-flip-game-ii.js)|Medium|
285286
295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard|
286287
297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard|
287288
299|[Bulls and Cows](./solutions/0299-bulls-and-cows.js)|Medium|

solutions/0294-flip-game-ii.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 294. Flip Game II
3+
* https://leetcode.com/problems/flip-game-ii/
4+
* Difficulty: Medium
5+
*
6+
* You are playing a Flip Game with your friend.
7+
*
8+
* You are given a string currentState that contains only '+' and '-'. You and your friend take
9+
* turns to flip two consecutive "++" into "--". The game ends when a person can no longer make
10+
* a move, and therefore the other person will be the winner.
11+
*
12+
* Return true if the starting player can guarantee a win, and false otherwise.
13+
*/
14+
15+
/**
16+
* @param {string} currentState
17+
* @return {boolean}
18+
*/
19+
var canWin = function(currentState) {
20+
const map = new Map();
21+
22+
return canWinFrom(currentState);
23+
24+
function canWinFrom(state) {
25+
if (map.has(state)) return map.get(state);
26+
27+
for (let i = 0; i < state.length - 1; i++) {
28+
if (state[i] === '+' && state[i + 1] === '+') {
29+
const nextState = state.slice(0, i) + '--' + state.slice(i + 2);
30+
if (!canWinFrom(nextState)) {
31+
map.set(state, true);
32+
return true;
33+
}
34+
}
35+
}
36+
37+
map.set(state, false);
38+
return false;
39+
}
40+
};

0 commit comments

Comments
 (0)