算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。今天和大家聊的问题叫做 翻转游戏,我们先来看题面: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.你和朋友玩一个叫做「翻转游戏」的游戏,游戏规则:给定一个只有 + 和 - 的字符串。 你和朋友轮流将 连续 的两个 “++” 反转成 “–”。 当一方无法进行有效的翻转时便意味着游戏结束,则另一方获胜。请你写出一个函数,来计算出第一次翻转后,字符串所有的可能状态。

 

示例

示例:
输入: s = "++++"
输出:
[
  "--++",
  "+--+",
  "++--"
]
注意:如果不存在可能的有效操作,请返回一个空列表 []。

解题

这道题让我们把相邻的两个++变成--,真不是一道难题,我们就从第二个字母开始遍历,每次判断当前字母是否为+,和之前那个字母是否为+,如果都为加,则将翻转后的字符串存入结果中即可,参见代码如下:

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

 

好了,今天的文章就到这里。