Problem Description:
You is playing the following Flip Game with your Friend:given a string this contains only these both characters: an +
D -
, you and your friend take turns to flip the consecutive "++"
into "--"
. The game ends when a person can no longer make a move and therefore the other person would be the 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 []
.
The idea was quite straightforward:just traverse s
and each time we see +
a consecutive S, convert them to s and add the resulting string to the final result moves
. But remember to recover the string after that.
The C + + code is as follows.
classSolution { Public: Vector<string> generatepossiblenextmoves (strings) {vector<string>moves; intn =s.length (); for(inti =0; I < n-1; i++) { if(S[i] = ='+'&& S[i +1] =='+') {S[i]= S[i +1] ='-'; Moves.push_back (s); S[i]= S[i +1] ='+'; } } returnmoves; }};
the Well I also try-to-write a python solution since Python supports sequential comparisons, which is quite convenient. But Python does not support modifying a string and I can only use and to do the list
join
same thing.< /c4>
classsolution (object):defgeneratepossiblenextmoves (self, s):""": Type S:STR:RTYPE:LIST[STR]"""moves, N, S=[], Len (s), list (s) forIinchXrange (n-1): ifS[i] = = s[i + 1] = ='+': S[i]= S[i + 1] ='-'moves+="'. Join (s), S[i]= S[i + 1] ='+' returnMoves
[Leetcode] Flip Game