2337. Move Pieces to Obtain a String

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
class Solution {
public boolean canChange(String start, String target) {
if (!start.replaceAll("_", "").equals(target.replaceAll("_", ""))) {
return false;
}

// 此时已保证去掉下划线后的所有字符相等,现在只需检查相对顺序即可
int i = 0, j = 0;
while (i < start.length()) {
while (i < start.length() && start.charAt(i) == '_') {
i++;
}
// 寻找到 L 或 R
if (i == start.length()) {
return true;
}
while (target.charAt(j) == '_') {
j++;
}

if (i != j) {
// 需要保证可移动
if (start.charAt(i) == 'L' && i < j) {
// 因为 L 只能向左移动,所以此处返回 false
return false;
}
if (start.charAt(i) == 'R' && i > j) {
// 因为 R 只能向右移动,所以此处返回 false
return false;
}
}

i++;
j++;
}

return true;
}
}

References

2337. Move Pieces to Obtain a String