[LeetCode] Flip Game
Problem Description:
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 two consecutive "++"
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.
For example, given s = "++++"
, after one move, it may become one of the following states:
[ "--++", "+--+", "++--" ]
If there is no valid move, return an empty list []
.
The idea is quite straightforward: just traverse s
and each time when we see two consecutive+
s, convert them to -
s and add the resulting string to the final result moves
. But remember to recover the string after that.
The C++ code is as follows.
class Solution { public: vector<string> generatePossibleNextMoves(string s) { vector<string> moves; int n = s.length(); for (int i = 0; i < n - 1; i++) { if (s[i] == '+' && s[i + 1] == '+') { s[i] = s[i + 1] = '-'; moves.push_back(s); s[i] = s[i + 1] = '+'; } } return moves; } };
Well I also try to write a Python solution since Python supports sequential comparisons, which is quite convenient. But Python does not support modifying a string and I can only use list
and join
to do the same thing.
class Solution(object): def generatePossibleNextMoves(self, s): """ :type s: str :rtype: List[str] """ moves, n, s = [], len(s), list(s) for i in xrange(n - 1): if s[i] == s[i + 1] == '+': s[i] = s[i + 1] = '-' moves += ''.join(s), s[i] = s[i + 1] = '+' return moves
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· Ollama系列05:Ollama API 使用指南
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率