Move Pieces to Obtain a String

medium two pointers string

Problem

You are given two strings start and target of the same length, built only from the characters 'L', 'R', and '_'. A piece 'L' may repeatedly slide one cell to the left when the cell directly left of it is blank, and a piece 'R' may slide one cell to the right into a blank. Pieces can never jump over each other.

Return true if some sequence of such moves can turn start into target, and false otherwise.

Inputstart = "_L__R__R_", target = "L______RR"
Outputtrue
The L slides left from index 1 to 0, the first R slides right from index 4 to 7, and the last R slides right from index 7 to 8.

def can_change(start, target):
    n = len(start)
    i = j = 0
    while i < n or j < n:
        while i < n and start[i] == '_':
            i += 1
        while j < n and target[j] == '_':
            j += 1
        if i == n or j == n:
            return i == n and j == n
        if start[i] != target[j]:
            return False
        if start[i] == 'L' and i < j:
            return False
        if start[i] == 'R' and i > j:
            return False
        i += 1
        j += 1
    return True
function canChange(start, target) {
  const n = start.length;
  let i = 0, j = 0;
  while (i < n || j < n) {
    while (i < n && start[i] === '_') i++;
    while (j < n && target[j] === '_') j++;
    if (i === n || j === n) return i === n && j === n;
    if (start[i] !== target[j]) return false;
    if (start[i] === 'L' && i < j) return false;
    if (start[i] === 'R' && i > j) return false;
    i++; j++;
  }
  return true;
}
boolean canChange(String start, String target) {
    int n = start.length();
    int i = 0, j = 0;
    while (i < n || j < n) {
        while (i < n && start.charAt(i) == '_') i++;
        while (j < n && target.charAt(j) == '_') j++;
        if (i == n || j == n) return i == n && j == n;
        if (start.charAt(i) != target.charAt(j)) return false;
        if (start.charAt(i) == 'L' && i < j) return false;
        if (start.charAt(i) == 'R' && i > j) return false;
        i++; j++;
    }
    return true;
}
bool canChange(string start, string target) {
    int n = start.size();
    int i = 0, j = 0;
    while (i < n || j < n) {
        while (i < n && start[i] == '_') i++;
        while (j < n && target[j] == '_') j++;
        if (i == n || j == n) return i == n && j == n;
        if (start[i] != target[j]) return false;
        if (start[i] == 'L' && i < j) return false;
        if (start[i] == 'R' && i > j) return false;
        i++; j++;
    }
    return true;
}
Time: O(n) Space: O(1)