# [LeetCode] 293. Flip Game 翻转游戏

2021年09月15日 阅读数：1

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.html

Write a function to compute all possible states of the string after one valid move.java

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

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

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

java:this

```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] = '-';
arr[i] = '+';
arr[i - 1] = '+';
}
}

return res;
}
}
```

Python:url

```class Solution(object):
def generatePossibleNextMoves(self, s):
"""
:type s: str
:rtype: List[str]
"""
res = []
i, n = 0, len(s) - 1
while i < n:                                    # O(n) time
if s[i] == '+':
while i < n and s[i+1] == '+':          # O(c) time
res.append(s[:i] + '--' + s[i+2:])  # O(n) time and space
i += 1
i += 1
return res
```

Python:spa

```# Time:  O(c * m * n + n) = O(c * n + n), where m = 2 in this question
# Space: O(n)
# This solution compares O(m) = O(2) times for two consecutive "+", where m is length of the pattern
class Solution2(object):
def generatePossibleNextMoves(self, s):
"""
:type s: str
:rtype: List[str]
"""
return [s[:i] + "--" + s[i+2:] for i in xrange(len(s) - 1) if s[i:i+2] == "++"]
```

C++:code

```// Time:  O(c * n + n) = O(n * (c+1)), n is length of string, c is count of "++"
// Space: O(1), no extra space excluding the result which requires at most O(n^2) space
class Solution {
public:
vector<string> generatePossibleNextMoves(string s) {
vector<string> res;
int n = s.length();
for (int i = 0; i < n - 1; ++i) {  // O(n) time
if (s[i] == '+') {
for (;i < n - 1 && s[i + 1] == '+'; ++i) {  // O(c) time
s[i] = s[i + 1] = '-';
res.emplace_back(s);  // O(n) to copy a string
s[i] = s[i + 1] = '+';
}
}
}
return res;
}
};
```

C++:

```class Solution {
public:
vector<string> generatePossibleNextMoves(string s) {
vector<string> res;
for (int i = 1; i < s.size(); ++i) {
if (s[i] == '+' && s[i - 1] == '+') {
res.push_back(s.substr(0, i - 1) + "--" + s.substr(i + 1));
}
}
return res;
}
};
```

[LeetCode] 294. Flip Game II 翻转游戏 II