-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path293. Flip Game.java
executable file
·110 lines (94 loc) · 2.74 KB
/
293. Flip Game.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
E
tags: String
#### String
- 可以用 sb.replace(i, j, "replacement string")
- 简单按 window=2 来扫描
- 原来只需要从'++'转到'--'的情况
- O(n)
```
/*
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:
[
"--++",
"+--+",
"++--"
]
*/
// 99.83
class Solution {
public List<String> generatePossibleNextMoves(String s) {
List<String> rst = new ArrayList<>();
if (s == null || s.length() < 2) {
return rst;
}
StringBuffer sb = new StringBuffer(s);
for (int i = 0; i < s.length() - 1; i++) {
String str = s.substring(i, i + 2);
if (str.equals("++")) {
sb.replace(i, i + 2, "--");
rst.add(sb.toString());
sb.replace(i, i + 2, "++");
}
}
return rst;
}
}
// 12.06.2015, slower than the previous one
public class Solution {
public List<String> generatePossibleNextMoves(String s) {
List<String> rst = new ArrayList<String>();
if (s == null || s.length() == 0) {
return rst;
}
ArrayList<Integer> list = new ArrayList<Integer>();
StringBuffer sb = new StringBuffer(s);
while (sb.indexOf("++") != -1) {
int index = sb.indexOf("++");
list.add(index);
sb.replace(index, index + 1, "*");
}
for (int index : list) {
rst.add(s.substring(0, index) + "--" + s.substring(index + 2));
}
return rst;
}
}
/*
Thoughts:
Two pointers to check if p1 and p2 match target patern. If so, add.
Need to ask: are we only looking to change to '--' from '++'?
*/
public class Solution {
public static List<String> generatePossibleNextMoves(String s) {
List<String> rst = new ArrayList<String>();
if (s == null || s.length() < 1) {
return rst;
}
char[] arr = s.toCharArray();
search('+','-',arr,rst);
return rst;
}
public static void search(char target, char replace, char[] arr, List<String> rst) {
int p1 = 0;
int p2 = 1;
while (p2 <= arr.length - 1) {
if (arr[p1] == target && arr[p2] == target) {
arr[p1] = replace;
arr[p2] = replace;
rst.add(new String(arr));
arr[p1] = target;
arr[p2] = target;
}
p1++;
p2++;
}
}
}
```