293. Flip Game - jiejackyzhang/leetcode-note GitHub Wiki

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 [].

解题思路为: 遍历一次string,把两个连续的"++"变为"--",把结果加入list,然后再把"--"改回去,继续下面的遍历。

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