914. 翻转游戏

描述

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

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

您在真实的面试中是否遇到过这个题?  

样例

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

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

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

其实我有点懵没明白这道题目的用意何在,但我还是按照它的要求写了程序:

class Solution {
public:
    /**
     * @param s: the given string
     * @return: all the possible states of the string after one valid move
     */
    vector<string> generatePossibleNextMoves(string &s) {
        // write your code here
        vector<string> result;
        if(s.length()<2) return result;
        for(int i=0;i<s.length()-1;i++){
            if(s[i]=='+'&&s[i+1]=='+'){
                string tmp=s;
                tmp[i]='-';
                tmp[i+1]='-';
                result.push_back(tmp);
            }
        }
        return result;
    }
};
用tmp比较麻烦可以使用substr注意它的区间表示从第一个参数开始 第二个参数的长度。
class Solution {
public:
    /**
     * @param s: the given string
     * @return: all the possible states of the string after one valid move
     */
    vector<string> generatePossibleNextMoves(string &s) {
        // write your code here
        vector<string> result;
        if(s.length()<2) return result;
        for(int i=0;i<s.length()-1;i++){
            if(s[i]=='+'&&s[i+1]=='+'){
                result.push_back(s.substr(0, i) + "--" + s.substr(i + 2));
            }
        }
        return result;
    }
};


猜你喜欢

转载自blog.csdn.net/vestlee/article/details/80765870