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:
parent
e5ef5167a7
commit
97dc8014b2
1 changed files with 54 additions and 0 deletions
54
java/move-pieces-to-obtain-a-string.java
Normal file
54
java/move-pieces-to-obtain-a-string.java
Normal 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();
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue