[LeetCode] 293. 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.

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 [].

 

這道題讓我們把相鄰的兩個 ++ 變成 --,真不是一道難題,就從第二個字母開始遍歷,每次判斷當前字母是否為+,和之前那個字母是否為+,如果都為加,則將翻轉后的字符串存入結果中即可,參見代碼如下:

 

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

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/293

 

類似題目:

Flip Game II

 

參考資料:

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

https://leetcode.com/problems/flip-game/discuss/73901/4-lines-in-Java

https://leetcode.com/problems/flip-game/discuss/73902/Simple-solution-in-Java

 

LeetCode All in One 題目講解匯總(持續更新中...) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM