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;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值