码迷,mamicode.com
首页 > 其他好文 > 详细

293. Flip Game

时间:2015-12-13 08:29:08      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

链接: http://leetcode.com/problems/flip-game/

题解:

把"++"flip成"--"。把输入String转化为char[]就很好操作了。 其实用String也好操作,看到Stefan写了一个4行的,很精彩。

Time Complexity - O(n), Space Complexity - O(n)。

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

 

Reference:

https://leetcode.com/discuss/64248/4-lines-in-java

https://leetcode.com/discuss/64335/simple-solution-in-java

293. Flip Game

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/5042265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!