-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathSwapAdjacentInLRString777.java
80 lines (70 loc) · 2.19 KB
/
SwapAdjacentInLRString777.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
/**
* In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a
* move consists of either replacing one occurrence of "XL" with "LX", or
* replacing one occurrence of "RX" with "XR". Given the starting string start
* and the ending string end, return True if and only if there exists a
* sequence of moves to transform one string to the other.
*
* Example:
* Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
* Output: True
*
* Explanation:
* We can transform start to end following these steps:
* RXXLRXRXL ->
* XRXLRXRXL ->
* XRLXRXRXL ->
* XRLXXRRXL ->
* XRLXXRRLX
*
* Note:
* 1 <= len(start) = len(end) <= 10000.
* Both start and end will only consist of characters in {'L', 'R', 'X'}.
*/
public class SwapAdjacentInLRString777 {
public boolean canTransform(String start, String end) {
int len = start.length();
char[] starts = start.toCharArray();
char[] ends = end.toCharArray();
int ps = 0;
int pe = 0;
while (ps < len) {
while (ps < len && starts[ps] == 'X') {
ps++;
}
if (ps == len) break;
while (pe < len && ends[pe] == 'X') {
pe++;
}
if (pe == len) return false;
if (starts[ps] == 'R') {
if (ends[pe] != 'R' || pe < ps) return false;
} else { // starts[ps] == 'L'
if (ends[pe] != 'L' || pe > ps) return false;
}
ps++;
pe++;
}
while (pe < len) {
if (ends[pe++] != 'X') return false;
}
return true;
}
/**
* https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/114737/Simple-Java-Solution
*/
public boolean canTransform2(String start, String end) {
int r = 0;
int l = 0;
for (int i = 0; i < start.length(); i++){
if (start.charAt(i) == 'L') l++;
if (start.charAt(i) == 'R') r++;
if (end.charAt(i) == 'L') l--;
if (end.charAt(i) == 'R') r--;
if (l > 0 || r < 0 || (r > 0 && l != 0)) {
return false;
}
}
return l == 0 && r == 0;
}
}