Leetcode 2337 Move Pieces to Obtain a String Solution in Java | Hindi Coding Community

0

 



You are given two strings start and target, both of length n. Each string consists only of the characters 'L''R', and '_' where:

  • The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right.
  • The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces.

Return true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false.

 

Example 1:

Input: start = "_L__R__R_", target = "L______RR"
Output: true
Explanation: We can obtain the string target from start by doing the following moves:
- Move the first piece one step to the left, start becomes equal to "L___R__R_".
- Move the last piece one step to the right, start becomes equal to "L___R___R".
- Move the second piece three steps to the right, start becomes equal to "L______RR".
Since it is possible to get the string target from start, we return true.

Example 2:

Input: start = "R_L_", target = "__LR"
Output: false
Explanation: The 'R' piece in the string start can move one step to the right to obtain "_RL_".
After that, no pieces can move anymore, so it is impossible to obtain the string target from start.

Example 3:

Input: start = "_R", target = "R_"
Output: false
Explanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.

 

Constraints:

  • n == start.length == target.length
  • 1 <= n <= 105
  • start and target consist of the characters 'L''R', and '_'.



Java Code :



class Solution {
class Pair{
char c;
int idx;
Pair(char cc, int idx){
this.c = cc;
this.idx = idx;
}
}
public boolean canChange(String start, String target) {
int idx = 0;
int n = start.length();
Stack<Pair> s1 = new Stack<>();
Stack<Pair> s2 = new Stack<>();
// Fill the stacks
for(int i = n-1; i >= 0; i--){
if(start.charAt(i) == 'L' || start.charAt(i) == 'R'){
s1.push(new Pair(start.charAt(i), i));
}
if(target.charAt(i) == 'L' || target.charAt(i) == 'R'){
s2.push(new Pair(target.charAt(i), i));
}
}
// Early return
if(s1.size() != s2.size()){
return false;
}
// Validates both the sequinces
while(!s1.isEmpty()){
Pair s = s1.pop();
Pair e = s2.pop();
if(s.c != e.c){
return false;
}
if(s.c == 'L' && e.c == 'L'){
if(e.idx > s.idx){
return false;
}
}
if(s.c == 'R' && e.c == 'R'){
if(e.idx < s.idx){
return false;
}
}
}
return true;
}
}



Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !