java: add «2337. Move Pieces to Obtain a String»

URL:	https://leetcode.com/problems/move-pieces-to-obtain-a-string/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-05 21:23:17 +01:00
parent e5ef5167a7
commit 97dc8014b2
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,54 @@
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();
}
}