844. 比较含退格的字符串
# 844. 比较含退格的字符串 (opens new window)
# 1.指针
从后向前遍历,遇到‘#’需要进行跳过,这里需要注意的是‘#’自身不会进行跳过,比如"bxo#j##tw"这个例子。因此执行跳跃时不能直接更新指针point,而是需要遍历每一个字符,处理跳跃的逻辑如下:
- 如果当前字符为#,那么count加一
- 当前字符串不为#,那么需要扣减count;如果为0则跳跃结束。
class Solution {
public boolean backspaceCompare(String s, String t) {
int point1=s.length()-1,point2=t.length()-1;
while(point1>=0&&point2>=0){
if(s.charAt(point1)!='#'&&t.charAt(point2)!='#'){
if(s.charAt(point1)!=t.charAt(point2)) return false;
point1--;
point2--;
}
if(point1>=0&&s.charAt(point1)=='#'){
int count1=0;
while(point1>=0){
if(s.charAt(point1)=='#'){
point1--;
count1++;
}
else{
//只要非#字符才能
if(count1>0){
count1--;
point1--;
}
else break;
}
}
}
if(point2>=0&&t.charAt(point2)=='#'){
int count2=0;
while(point2>=0){
if(t.charAt(point2)=='#'){
point2--;
count2++;
}
else{
if(count2>0){
count2--;
point2--;
}
else break;
}
}
}
}
if(point1==-1&&point2==-1) return true;
else return false;
}
}
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
44
45
46
47
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
44
45
46
47
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57