​LeetCode刷题实战293:翻转游戏

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 翻转游戏,我们先来看题面:

https://leetcode-cn.com/problems/flip-game/

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

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-280题汇总,希望对你有点帮助!

LeetCode刷题实战281:锯齿迭代器

LeetCode刷题实战282:给表达式添加运算符

LeetCode刷题实战283:移动零

LeetCode刷题实战284:顶端迭代器

LeetCode刷题实战285:二叉搜索树中的顺序后继

LeetCode刷题实战286:墙和门

LeetCode刷题实战287:寻找重复数

LeetCode刷题实战288:单词的唯一缩写

LeetCode刷题实战289:生命游戏

LeetCode刷题实战290:单词规律

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程IT圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值