2023年8月21日每日一题--2337. 移动片段得到字符串

leetcode链接:2337. 移动片段得到字符串

题目分析



方案一

看了别人题解之后做的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean canChange(String start, String target) {
int length = start.length();
int indexStart = 0, indexTarget = 0;

while (true) {
while (indexStart < length && start.charAt(indexStart) == '_') indexStart++;
while (indexTarget < length && target.charAt(indexTarget) == '_') indexTarget++;
if (indexStart == length && indexTarget == length) return true;
if (indexStart == length || indexTarget == length || start.charAt(indexStart) != target.charAt(indexTarget)) return false;
if ((start.charAt(indexStart) == 'L' && indexStart < indexTarget) || (start.charAt(indexStart) == 'R' && indexStart > indexTarget)) return false;
indexStart++;
indexTarget++;
}
}
}

结果

分析

时间复杂度:
O( n )

空间复杂度:
O( 1 )

官方题解

https://leetcode.cn/problems/move-pieces-to-obtain-a-string/solutions/2397699/python3javacgotypescript-yi-ti-yi-jie-sh-xlzu/

https://leetcode.cn/problems/move-pieces-to-obtain-a-string/solutions/1855012/yi-dong-pian-duan-de-dao-zi-fu-chuan-by-0j7py/

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public 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) {
if (start.charAt(i) != target.charAt(j)) {
return false;
}
char c = start.charAt(i);
if ((c == 'L' && i < j) || (c == 'R' && i > j)) {
return false;
}
i++;
j++;
}
}
while (i < n) {
if (start.charAt(i) != '_') {
return false;
}
i++;
}
while (j < n) {
if (target.charAt(j) != '_') {
return false;
}
j++;
}
return true;
}
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/move-pieces-to-obtain-a-string/solutions/1855012/yi-dong-pian-duan-de-dao-zi-fu-chuan-by-0j7py/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


2023年8月21日每日一题--2337. 移动片段得到字符串
http://yuanql.top/2023/08/21/02_02_leetcode_每日一题/2023年8月21日每日一题--2337. 移动片段得到字符串/
作者
Qingli Yuan
发布于
2023年8月21日
许可协议