[LeetCode] 2337. Move Pieces to Obtain a String
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
andtarget
consist of the characters'L'
,'R'
, and'_'
.
移动片段得到字符串。
给你两个字符串
start
和target
,长度均为n
。每个字符串 仅 由字符'L'
、'R'
和'_'
组成,其中:
- 字符
'L'
和'R'
表示片段,其中片段'L'
只有在其左侧直接存在一个 空位 时才能向 左 移动,而片段'R'
只有在其右侧直接存在一个 空位 时才能向 右 移动。- 字符
'_'
表示可以被 任意'L'
或'R'
片段占据的空位。如果在移动字符串
start
中的片段任意次之后可以得到字符串target
,返回true
;否则,返回false
。
思路是双指针。
注意因为我们不能让任何的 L 跨过 R,也不能让任何的 R 跨过 L,所以本质上如果去掉所有的下划线,start 和 target 最后剩下的部分应该是一样的。所以这里我们用两个指针 i, j 分别指向 start 和 target,如果遇到下划线就跳过,如果两边都不是下划线,则比较两边的字母是否一样;还有一种情形是两个指针都指向了字母,但是因为题目只允许 start 中 L 左移,R 右移,那么如下这两种情形就需要返回 false
- 如果 start 中遇到的 L 的下标比 target 中遇到的 L 的下标小
- 如果 start 中遇到的 R 的下标比 target 中遇到的 R 的下标大
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public boolean canChange(String start, String target) { 3 int i = 0; 4 int j = 0; 5 int n = target.length(); 6 while (i <= n && j <= n) { 7 while (i < n && start.charAt(i) == '_') { 8 i++; 9 } 10 while (j < n && target.charAt(j) == '_') { 11 j++; 12 } 13 14 if (i == n || j == n) { 15 return i == n && j == n; 16 } 17 18 if (start.charAt(i) != target.charAt(j)) { 19 return false; 20 } 21 if (start.charAt(i) == 'L') { 22 if (j > i) { 23 return false; 24 } 25 } 26 if (start.charAt(i) == 'R') { 27 if (j < i) { 28 return false; 29 } 30 } 31 i++; 32 j++; 33 } 34 return i == n && j == n; 35 } 36 }