2337. Move Pieces to Obtain a String | Daily LeetCode Solution | Java #coding

preview_player
Показать описание

This problem asks us to determine if it is possible to transform the start string into the target string by following specific movement rules for the pieces 'L' and 'R'.

Approach:
Filter Non-Underscore Characters:

Remove all underscores ('_') from both strings.
Compare the remaining characters. If the sequence does not match, return false.
Two-Pointer Traversal:

Use two pointers, i and j, to traverse start and target, skipping all underscores.
Compare the characters at i and j. If they don't match, return false.
Movement Rules:

For 'L': It can only move left. If the index in start (i) is smaller than the corresponding index in target (j), return false.
For 'R': It can only move right. If the index in start (i) is greater than the corresponding index in target (j), return false.
Final Validation:

Ensure that the pointers reach the end of both strings together.
Code Explanation:
Input: Two strings, start and target.
Output: Boolean indicating whether the transformation is possible.
Complexity:
Time: 𝑂(𝑛), where 𝑛 is the length of the strings.
Space: 𝑂(1), aside from the filtered strings used for comparison.

📅 Daily Solutions:
Subscribe for concise, step-by-step explanations and Java implementations of LeetCode's daily challenges!

👥 Join the Discussion:
How would you optimize this approach? Let us know in the comments below.
Рекомендации по теме
Комментарии
Автор

class Solution {
public boolean canChange(String start, String target) {

//Remove underscores and check if the order of 'L' and 'R' matches
String filteredStart = start.replace("_", "");
String filteredTarget = target.replace("_", "");

return false;

int n = start.length();
int i = 0, j = 0;

while(i < n && j < n) {
//Skip underscores in both strings
while(i < n && start.charAt(i) == '_')
i++;
while(j < n && target.charAt(j) == '_')
j++;

//If one reached the end and the other does not, return false
if(i == n ||j == n)
break;

//Check the movement rule for 'L' and 'R'
if(start.charAt(i) != target.charAt(j))
return false;
//'L' can only move left
if(start.charAt(i) == 'L' && i < j)
return false;
if(start.charAt(i) == 'R' && i > j)
return false;

//Move to the next character
i++;
j++;
}
return true;
}
}

AlgoXploration
join shbcf.ru