Question:
You are playing the following Flip Game with your friend: Given a string that contains only these two characters: +
and -
, you and your friend take turns to flip two consecutive "++"
into "--"
. The game ends when a person can no longer make a move and therefore the other person will be 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.
题目要求是,一个字符串只是由“+”和“-”组成,两个人轮流将字符串中的++改为“-”,如果有人不能再翻转字符,则游戏结束。写一个函数来判断第一个翻转的人是否是赢家。
答题思路很简单,就是第一个人如果翻转后,就不能再翻转了即可。
编程思路为:递归,从字符串的第0个位置开始扫描,如果有“++”,则记录其位置,并判断剩余字符串+“-”是否可以翻转,若不能翻转,则第一个人赢了,若可以,则继续。否则输。
代码如下:
<span style="font-size:14px;">class Solution {
public:
bool canWin(string s) {
for (int i = -1; (i = s.find("++", i + 1)) >= 0; )
if (!canWin(s.substr(0, i) + '-' + s.substr(i+2)))
return true;
return false;
}
};</span>