Skip to content

Commit 5c9f6b2

Browse files
committed
problem: 0844 backspace string compare
1 parent faf75ce commit 5c9f6b2

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# 0844. Backspace String Compare
2+
3+
* Difficulty: easy
4+
* Link: https://leetcode.com/problems/backspace-string-compare/
5+
* Topics: Array-String
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: two string
11+
- OUTPUT: boolean
12+
13+
# Naive Solution
14+
15+
### Thought Process
16+
17+
1. 每個 string 皆從最後面開始往回看
18+
2. 若為 # 紀錄若遇到文字要往回走一格
19+
3. 比對兩個 string 當下在的文字是否一樣
20+
- Implement
21+
22+
```python
23+
class Solution:
24+
def backspaceCompare(self, s: str, t: str) -> bool:
25+
sIdx = len(s)-1
26+
tIdx = len(t)-1
27+
sSkip = 0
28+
tSkip = 0
29+
while sIdx >=0 or tIdx >=0:
30+
while sIdx >=0:
31+
if s[sIdx] == '#':
32+
sSkip += 1
33+
sIdx -= 1
34+
elif sSkip > 0:
35+
sSkip -= 1
36+
sIdx -= 1
37+
else:
38+
break
39+
while tIdx >=0:
40+
if t[tIdx] == '#':
41+
tSkip += 1
42+
tIdx -= 1
43+
elif tSkip > 0:
44+
tSkip -= 1
45+
tIdx -= 1
46+
else:
47+
break
48+
if sIdx >= 0 and tIdx >= 0 and s[sIdx] != t[tIdx]:
49+
return False
50+
if (sIdx >=0 ) != (tIdx >=0):
51+
return False
52+
sIdx -= 1
53+
tIdx -= 1
54+
return True
55+
```
56+
57+
58+
### Complexity
59+
60+
- Time complexity: $O(n)$
61+
- Space complexity:$O(1)$

0 commit comments

Comments
 (0)