293. Flip Game

时间:2021-12-10 21:22:13

题目:

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 twoconsecutive "++" 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 compute all possible states of the string after one valid move.

For example, given s = "++++", after one move, it may become one of the following states:

[
"--++",
"+--+",
"++--"
]

If there is no valid move, return an empty list [].

链接: http://leetcode.com/problems/flip-game/

题解:

把"++"flip成"--"。把输入String转化为char[]就很好操作了。 其实用String也好操作,看到Stefan写了一个4行的,很精彩。

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
public List<String> generatePossibleNextMoves(String s) {
List<String> res = new ArrayList<>();
char[] arr = s.toCharArray();
for(int i = 1; i < s.length(); i++) {
if(arr[i] == '+' && arr[i - 1] == '+') {
arr[i] = '-';
arr[i - 1] = '-';
res.add(String.valueOf(arr));
arr[i] = '+';
arr[i - 1] = '+';
}
} return res;
}
}

二刷:

题目的意思是,record all states after one valid move, 所以我们只需要flip一次。 先把String转换为数组,从1开始到最后,把两个连续的'+'变为'-',记录下这个结果,再backtracking把那两个'-'改回去,接着计算下面的结果。遍历完一次数组之后就可以了。

Java:

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
public List<String> generatePossibleNextMoves(String s) {
List<String> res = new ArrayList<>();
if (s == null || s.length() < 2) {
return res;
}
char[] arr = s.toCharArray();
for (int i = 1; i < arr.length; i++) {
if (arr[i] == '+' && arr[i - 1] == '+') {
arr[i] = '-';
arr[i - 1] = '-';
res.add(String.valueOf(arr));
arr[i] = '+';
arr[i - 1] = '+';
}
}
return res;
}
}

三刷:

跟之前一样

Java:

public class Solution {
public List<String> generatePossibleNextMoves(String s) {
List<String> res = new ArrayList<>();
if (s == null || s.length() < 2) return res;
char[] str = s.toCharArray();
for (int i = 1; i < str.length; i++) {
if (str[i] == '+' && str[i - 1] == '+') {
str[i - 1] = '-';
str[i] = '-';
res.add(new String(str));
str[i - 1] = '+';
str[i] = '+';
}
}
return res;
}
}

Reference:

https://leetcode.com/discuss/64248/4-lines-in-java

https://leetcode.com/discuss/64335/simple-solution-in-java