You is playing the following Flip Game with your Friend:given a string this contains only these both characters: an +
D -
, you and your friend take turns to the flip twoconsecutive into "++"
"--"
. The game ends when a person can no longer make a move and therefore the other person would be the the winner.
Write a function to determine if the starting player can guarantee a win.
For example, given s = "++++"
, return true. The starting player can guarantee a win by flipping the middle to "++"
become "+--+"
.
Follow up:
Derive your algorithm ' s runtime complexity.
This problem is the expansion of the previous flip game, let us determine whether the player can win, then we can be poor to lift all the situation, using backtracking to solve the problem, our thinking is similar to the above problem, but also from the second letter began to traverse the entire string, if the current letter and the previous letter is A +, Then we recursive call the two positions into--the string, if return false, indicating that the current player can win, the end loop returns false, see the code as follows:
Solution One:
classSolution { Public: BOOLCanwin (strings) { for(inti =1; I < s.size (); ++i) {if(S[i] = ='+'&& S[i-1] =='+'&&!canwin (S.substr (0I1) +"--"+ S.SUBSTR (i +1))) { return true; } } return false; }};
The second solution is the same as the first solution, just use the Find function to find the location of + +, then assign the location to I, and then recursively call the Canwin function, see the code below:
Solution Two:
classSolution { Public: BOOLCanwin (strings) { for(inti =-1; (i = S.find ("++", i +1)) >=0;) { if(!canwin (S.substr (0, i) +"--"+ S.SUBSTR (i +2))) { return true; } } return false; }};
Similar topics:
Flip Game
Resources:
Https://leetcode.com/discuss/64350/short-java-%26-ruby
Https://leetcode.com/discuss/64330/4-line-java-solution
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Flip game flips the second