diff --git a/java/move-pieces-to-obtain-a-string.java b/java/move-pieces-to-obtain-a-string.java new file mode 100644 index 0000000..11d211a --- /dev/null +++ b/java/move-pieces-to-obtain-a-string.java @@ -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(); + } +}