-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwapAdjacentInString.java
More file actions
41 lines (37 loc) · 1.2 KB
/
SwapAdjacentInString.java
File metadata and controls
41 lines (37 loc) · 1.2 KB
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
package solutions;
// [Problem] https://leetcode.com/problems/swap-adjacent-in-lr-string
class SwapAdjacentInString {
// Two pointers
// O(n) time, O(1) space
public boolean canTransform(String start, String end) {
int i = 0, j = 0, len = start.length();
while (i < len || j < len) {
while (i < len && start.charAt(i) == 'X') {
i++;
}
while (j < len && end.charAt(j) == 'X') {
j++;
}
if (i >= len || j >= len) {
break;
}
if (start.charAt(i) != end.charAt(j)) {
return false;
} else if (start.charAt(i) == 'R' && i > j) {
return false;
} else if (start.charAt(i) == 'L' && i < j) {
return false;
}
i++;
j++;
}
return i == j;
}
// Test
public static void main(String[] args) {
SwapAdjacentInString solution = new SwapAdjacentInString();
String start = "RXXLRXRXL", end = "XRLXXRRLX";
boolean output = solution.canTransform(start, end);
System.out.println("Test 1 passed? " + (output == true));
}
}