Skip to content

2337. Move Pieces to Obtain a String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  bool canChange(string start, string target) {
    const int n = start.length();
    int i = 0;  // start's index
    int j = 0;  // target's index

    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] == 'R' && i > j)
        return false;
      if (start[i] == 'L' && i < j)
        return false;
      ++i;
      ++j;
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public boolean canChange(String start, String target) {
    final int n = start.length();
    int i = 0; // start's index
    int j = 0; // target's index

    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) == 'R' && i > j)
        return false;
      if (start.charAt(i) == 'L' && i < j)
        return false;
      ++i;
      ++j;
    }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
  def canChange(self, start: str, target: str) -> bool:
    n = len(start)
    i = 0  # start's index
    j = 0  # target's index

    while i <= n and 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] == 'R' and i > j:
        return False
      if start[i] == 'L' and i < j:
        return False
      i += 1
      j += 1

    return True