2337. Move Pieces to Obtain a String #916
-
Topics: You are given two strings
Return Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to check if we can transform the string
Plan:
Algorithm Explanation:
Let's implement this solution in PHP: 2337. Move Pieces to Obtain a String <?php
/**
* @param String $start
* @param String $target
* @return Boolean
*/
function canChange($start, $target) {
$n = strlen($start);
// Step 1: Remove `_` from both strings and compare
$startNoUnderscore = str_replace('_', '', $start);
$targetNoUnderscore = str_replace('_', '', $target);
if ($startNoUnderscore !== $targetNoUnderscore) {
return false;
}
// Step 2: Two-pointer traversal
$i = $j = 0;
while ($i < $n && $j < $n) {
// Move pointers to next non-underscore character
while ($i < $n && $start[$i] === '_') $i++;
while ($j < $n && $target[$j] === '_') $j++;
// If one pointer reaches the end but the other doesn't
if ($i < $n && $j < $n) {
// Check for mismatched positions
if ($start[$i] !== $target[$j]) return false;
// `L` should only move left; `R` should only move right
if (($start[$i] === 'L' && $i < $j) || ($start[$i] === 'R' && $i > $j)) {
return false;
}
}
$i++;
$j++;
}
return true;
}
// Test cases
var_dump(canChange("_L__R__R_", "L______RR")); // true
var_dump(canChange("R_L_", "__LR")); // false
var_dump(canChange("_R", "R_")); // false
?> Explanation:
Time Complexity:
Space Complexity:
Complexity Analysis:
Explanation of Test Cases:
This implementation is efficient and adheres to the problem constraints, making it suitable for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to check if we can transform the string
start
into the stringtarget
by moving pieces ('L' and 'R') as per the given rules. The main constraints to consider are:Plan:
Length Check: First, check if both strings have the same length. If they don't, return
false
immediately.Character Frequency Check: The number of 'L's, 'R's, and '_' in the
start
string must match the respective counts in thetarget
string because the pieces cannot be duplicated or destroyed, only moved.Piece Matching…