-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackspace-string-compare.py
More file actions
51 lines (42 loc) · 1.39 KB
/
backspace-string-compare.py
File metadata and controls
51 lines (42 loc) · 1.39 KB
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
48
49
50
51
class Solution:
# Time complexity: O(max(n, m)) where n and m are the length of s and t
# Space complexity: O(1)
def backspaceCompare(self, s: str, t: str) -> bool:
i, j = len(s)-1, len(t)-1
while i >= 0 or j >= 0:
c = 0
while i >= 0 and (s[i] == "#" or c > 0):
if s[i] == "#":
c += 1
else:
c -= 1
i -= 1
c = 0
while j >= 0 and (t[j] == "#" or c > 0):
if t[j] == "#":
c += 1
else:
c -= 1
j -= 1
if i >= 0 and j >= 0:
if s[i] != t[j]: return False
i, j = i-1, j-1
else:
break
return i < 0 and j < 0
# Time complexity: O(n + m) where n and m are the lengths of s and t
# Space cmoplexity: O(n + m)
def backspaceCompare2(self, s: str, t: str) -> bool:
ss, tt = [], []
for c in s:
if c == "#" and ss:
ss.pop()
elif c != "#":
ss.append(c)
for c in t:
if c == "#" and tt:
tt.pop()
elif c != "#":
tt.append(c)
print(ss, tt)
return "".join(ss) == "".join(tt)