【一次过】Lintcode 914. 翻转游戏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82862151

翻转游戏:给定一个只包含两种字符的字符串:+-,你和你的小伙伴轮流翻转"++"变成"--"。当一个人无法采取行动时游戏结束,另一个人将是赢家。

编写一个函数,计算字符串在一次有效移动后的所有可能状态。

样例

给定 s = "++++", 在一次有效移动后,它会变成下列状态之一:

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

如果无法移动,则返回一个空列表[].


解题思路:

简单,注意更改字符串中的内容,需将String转换为StringBuilder操作。

public class Solution {
    /**
     * @param s: the given string
     * @return: all the possible states of the string after one valid move
     */
    public List<String> generatePossibleNextMoves(String s) {
        // write your code here
        List<String> res = new ArrayList<>();
        
        char[] ss = s.toCharArray();
        
        for(int p=1 ; p < ss.length ; p++){
            StringBuilder temp = new StringBuilder(s);
            
            if(ss[p-1]=='+' && ss[p]=='+'){
                temp.setCharAt(p-1,'-');
                temp.setCharAt(p,'-');
                res.add(temp.toString());
            }
        }
        
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/82862151