Skip to content

Commit 2d3ce8b

Browse files
committed
844. 比较含退格的字符串
1 parent 947c2f3 commit 2d3ce8b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

str/844_backspaceCompare.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution:
2+
def backspaceCompare(self, S: str, T: str) -> bool:
3+
def handle(s: str):
4+
res = list()
5+
for ch in s:
6+
if ch != '#':
7+
res.append(ch)
8+
elif res:
9+
res.pop()
10+
return "".join(res)
11+
12+
return handle(S) == handle(T)
13+
14+
def backspaceCompare_1(self, S: str, T: str) -> bool:
15+
i, j = len(S) - 1, len(T) - 1
16+
skip0 = skip1 = 0
17+
18+
while i >= 0 or j >= 0:
19+
while i >= 0:
20+
if S[i] == '#':
21+
skip0 += 1
22+
i -= 1
23+
elif skip0 > 0:
24+
i -= 1
25+
skip0 -= 1
26+
else:
27+
break
28+
while j >= 0:
29+
if T[j] == '#':
30+
skip1 += 1
31+
j -= 1
32+
elif skip1 > 0:
33+
j -= 1
34+
skip1 -= 1
35+
else:
36+
break
37+
if i >= 0 and j >= 0:
38+
if S[i] != T[j]:
39+
return False
40+
elif i >= 0 or j >= 0:
41+
return False
42+
i -= 1
43+
j -= 1
44+
return True
45+
46+
47+
if __name__ == '__main__':
48+
S = "ab#c"
49+
T = "ad#c"
50+
solution = Solution()
51+
print(solution.backspaceCompare_1(S, T))

0 commit comments

Comments
 (0)