标签:
题目:
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
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/5042265.html