LeetCode 777: Swap Adjacent in LR String Solution
Master LeetCode problem 777 (Swap Adjacent in LR String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
777. Swap Adjacent in LR String
Problem Explanation
Explanation:
- We can solve this problem by iterating through the
startandresultstrings in parallel to check if they can be transformed fromstarttoresult. - We need to keep track of the positions of 'L' and 'R' in both strings and compare them to see if 'L' in
startis always before 'L' inresult, and 'R' instartis always after 'R' inresult. - We also need to handle 'X' characters in both strings, which can be matched with either 'L' or 'R'.
- If at any point the positions do not match the required order, we return false, otherwise, we return true.
:
Solution Code
class Solution {
public boolean canTransform(String start, String end) {
int n = start.length();
int p1 = 0, p2 = 0;
while (p1 < n && p2 < n) {
while (p1 < n && start.charAt(p1) == 'X') p1++;
while (p2 < n && end.charAt(p2) == 'X') p2++;
if (p1 == n || p2 == n) {
return p1 == p2;
}
if (start.charAt(p1) != end.charAt(p2) || (start.charAt(p1) == 'L' && p1 < p2) || (start.charAt(p1) == 'R' && p1 > p2)) {
return false;
}
p1++;
p2++;
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 777 (Swap Adjacent in LR String)?
This page provides optimized solutions for LeetCode problem 777 (Swap Adjacent in LR String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 777 (Swap Adjacent in LR String)?
The time complexity for LeetCode 777 (Swap Adjacent in LR String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 777 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 777 in Java, C++, or Python.