1 Star 0 Fork 0

徐长贺/Leetcode

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
_294.java 1.67 KB
一键复制 编辑 原始数据 按行查看 历史
Fisher Coder 提交于 2018-12-03 23:29 +08:00 . refactor 294
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 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.
*/
public class _294 {
public static class Solution1 {
public boolean canWin(String s) {
List<String> res = new ArrayList<>();
char[] charArray = s.toCharArray();
for (int i = 0; i < s.length() - 1; i++) {
if (charArray[i] == '+' && charArray[i + 1] == '+') {
//change these two bits to '-'
charArray[i] = '-';
charArray[i + 1] = '-';
res.add(String.valueOf(charArray));
//change these two bits back to '+' for its next move
charArray[i] = '+';
charArray[i + 1] = '+';
}
}
/**The above part is the same of Flip Game I.
* The only added part is the following piece of logic (so-called backtracking.)*/
for (String str : res) {
if (!canWin(str)) {
return true;
}
}
return false;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/isulong/Leetcode.git
git@gitee.com:isulong/Leetcode.git
isulong
Leetcode
Leetcode
master

搜索帮助