Wednesday, November 14, 2018

777. Swap Adjacent in LR String

777Swap Adjacent in LR String
In a string composed of 'L''R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.
Example:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: True
Explanation:
We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
Note:
  1. 1 <= len(start) = len(end) <= 10000.
  2. Both start and end will only consist of characters in {'L', 'R', 'X'}.
-------------------------------
一道题意模糊的题
从start 变换到end,R只能往右挪,L只能往左挪

class Solution {
    public boolean canTransform(String s, String e) {
        int i = 0, j = 0;
        int n = s.length();
        
        while (i < n && j < n) {
            while (i < n && s.charAt(i) != 'R' && s.charAt(i) != 'L') {
                i++;
            }
            
            while (j < n && e.charAt(j) != 'R' && e.charAt(j) != 'L') {
                j++;
            }
            
            if (i < n && j < n) {
                if (s.charAt(i) != e.charAt(j)) return false;    
                if (s.charAt(i) == 'R' && i > j) return false;
                if (s.charAt(i) == 'L' && i < j) return false;
            } 

            if ((i < n && j >= n) || (i >= n && j < n)) return false;
            i++;
            j++;
        }
        
        return true;
    }
}

No comments:

Post a Comment