Matej Focko
97dc8014b2
URL: https://leetcode.com/problems/move-pieces-to-obtain-a-string/ Signed-off-by: Matej Focko <me@mfocko.xyz>
54 lines
1.1 KiB
Java
54 lines
1.1 KiB
Java
class Solution {
|
|
private int skip(String s, int i) {
|
|
while (i < s.length() && s.charAt(i) == '_') {
|
|
++i;
|
|
}
|
|
|
|
return i;
|
|
}
|
|
|
|
private boolean correctMove(String s, int si, String t, int ti) {
|
|
if (si >= s.length() || ti >= t.length()) {
|
|
// check if both are out of bounds
|
|
return si == s.length() && ti == t.length();
|
|
}
|
|
|
|
// wrong order of the characters
|
|
if (s.charAt(si) != t.charAt(ti)) {
|
|
return false;
|
|
}
|
|
|
|
// left has to move right
|
|
if (t.charAt(ti) == 'L' && si < ti) {
|
|
return false;
|
|
}
|
|
|
|
// right has to move left
|
|
if (t.charAt(ti) == 'R' && si > ti) {
|
|
return false;
|
|
}
|
|
|
|
// no issue has been found
|
|
return true;
|
|
}
|
|
|
|
public boolean canChange(String start, String target) {
|
|
int i = 0, j = 0;
|
|
while (i < start.length() && j < target.length()) {
|
|
i = skip(start, i);
|
|
j = skip(target, j);
|
|
|
|
if (!correctMove(start, i, target, j)) {
|
|
return false;
|
|
}
|
|
|
|
++i;
|
|
++j;
|
|
}
|
|
|
|
i = skip(start, i);
|
|
j = skip(target, j);
|
|
|
|
return i == start.length() && j == target.length();
|
|
}
|
|
}
|