From 97dc8014b2cdc39c52bae71b512ff8e13a500a59 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 5 Dec 2024 21:23:17 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2337.=20Move=20Pieces=20to?= =?UTF-8?q?=20Obtain=20a=20String=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/move-pieces-to-obtain-a-string/ Signed-off-by: Matej Focko --- java/move-pieces-to-obtain-a-string.java | 54 ++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 java/move-pieces-to-obtain-a-string.java 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(); + } +}