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 [].
一刷:
由于是输出一次move后的所有状态。
思路很简单,从0找到“++”所在的index i, 然后替换(在res中直接添加)为“--”,然后从i之后继续寻找“++ ”
public class Solution {
public List<String> generatePossibleNextMoves(String s) {
List<String> list = new ArrayList<>();
for(int i=-1; (i = s.indexOf("++", i+1))>=0;)
list.add(s.substring(0, i) + "--" + s.substring(i+2));
return list;
}
}
二刷
遍历去寻找连续的“+”
public class Solution {
public List<String> generatePossibleNextMoves(String s) {
List<String> list = new ArrayList<>();
for(int i=0; i<s.length()-1; i++){
if(s.charAt(i) == '+' && s.charAt(i+1) == '+'){
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, i)).append("--").append(s.substring(i+2));
list.add(sb.toString());
}
}
return list;
}
}
三刷
class Solution {
public List<String> generatePossibleNextMoves(String s) {
List<String> res = new ArrayList<>();
for(int i=0; i<s.length()-1; i++){
char[] chs = s.toCharArray();
if(chs[i] == '+' && chs[i+1] == '+'){
chs[i] = '-';
chs[i+1] = '-';
res.add(new String(chs));
}
}
return res;
}
}