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

给一个只含有'+', '-'的字符串,每次可翻动两个连续的'+',求有多少种翻法。

解法:

java:

public class Solution {
    public List<String> generatePossibleNextMoves(String s) {
        List<String> res = new ArrayList<>();
        char[] arr = s.toCharArray();
        for(int i = 1; i < s.length(); i++) {
            if(arr[i] == '+' && arr[i - 1] == '+') {
                arr[i] = '-';
                arr[i - 1] = '-';
                res.add(String.valueOf(arr));
                arr[i] = '+';
                arr[i - 1] = '+';
            }
        }
        
        return res;
    }
}

Python:

class Solution(object):
    def generatePossibleNextMoves(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        res = []
        i, n = 0, len(s) - 1
        while i < n:                                    # O(n) time
            if s[i] == '+':
                while i < n and s[i+1] == '+':          # O(c) time
                    res.append(s[:i] + '--' + s[i+2:])  # O(n) time and space
                    i += 1
            i += 1
        return res

Python:

# Time:  O(c * m * n + n) = O(c * n + n), where m = 2 in this question
# Space: O(n)
# This solution compares O(m) = O(2) times for two consecutive "+", where m is length of the pattern
class Solution2(object):
  def generatePossibleNextMoves(self, s):
      """
      :type s: str
      :rtype: List[str]
      """
      return [s[:i] + "--" + s[i+2:] for i in xrange(len(s) - 1) if s[i:i+2] == "++"]

C++:

// Time:  O(c * n + n) = O(n * (c+1)), n is length of string, c is count of "++"
 // Space: O(1), no extra space excluding the result which requires at most O(n^2) space
 class Solution {
  public:
      vector<string> generatePossibleNextMoves(string s) {
          vector<string> res;
          int n = s.length();
          for (int i = 0; i < n - 1; ++i) {  // O(n) time
              if (s[i] == '+') {
                  for (;i < n - 1 && s[i + 1] == '+'; ++i) {  // O(c) time
                      s[i] = s[i + 1] = '-';
                      res.emplace_back(s);  // O(n) to copy a string
                      s[i] = s[i + 1] = '+';
                  }
              }
          }
          return res;
      }
  };

C++:

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

  

类似题目:

[LeetCode] 294. Flip Game II 翻转游戏 II   

 

 

All LeetCode Questions List 题目汇总

posted @ 2018-09-18 08:14  轻风舞动  阅读(816)  评论(0编辑  收藏  举报