Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6cf4064

Browse files
Backspace-String-Compare
1 parent 775d7dd commit 6cf4064

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
3535

3636
- [x] [Two Pointers](Two-Pointers)
3737
- [x] [Squares of a Sorted Array](Two-Pointers/977-Squares-of-a-Sorted-Array.py)
38+
- [x] [Backspace String Compare](Two-Pointers/844-Backspace-String-Compare.py)
3839

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import itertools
2+
"Leetcode- https://leetcode.com/problems/backspace-string-compare/ "
3+
'''
4+
Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
5+
6+
Note that after backspacing an empty text, the text will continue empty.
7+
8+
Example 1:
9+
10+
Input: s = "ab#c", t = "ad#c"
11+
Output: true
12+
Explanation: Both s and t become "ac".
13+
'''
14+
# Solution-1
15+
def backspaceCompare(self, S, T):
16+
ansS = []
17+
for c in S:
18+
if c == '#':
19+
if ansS:
20+
ansS.pop()
21+
else:
22+
ansS.append(c)
23+
24+
ansT = []
25+
for c in T:
26+
if c == '#':
27+
if ansT:
28+
ansT.pop()
29+
else:
30+
ansT.append(c)
31+
32+
return ''.join(ansS) == ''.join(ansT)
33+
34+
#or#
35+
36+
37+
def backspaceCompare(self, S, T):
38+
def build(S):
39+
ans = []
40+
for c in S:
41+
if c != '#':
42+
ans.append(c)
43+
elif ans:
44+
ans.pop()
45+
return "".join(ans)
46+
return build(S) == build(T)
47+
48+
# T:O(M+N)
49+
# S:O(M+N)
50+
51+
# Solution-2
52+
def backspaceCompare(self, s, t):
53+
l1 = len(s) - 1
54+
l2 = len(t) - 1
55+
56+
while l1 > -1 or l2 > -1:
57+
# count how many backspace
58+
count = 0
59+
while l1 > -1:
60+
if s[l1] == "#":
61+
count += 1
62+
l1 -= 1
63+
else:
64+
if count == 0:
65+
# not backspace, move on
66+
break
67+
else:
68+
# there are backspaces, delete curr char.
69+
l1 -= 1
70+
count -= 1
71+
72+
count = 0
73+
while l2 > -1:
74+
if t[l2] == "#":
75+
count += 1
76+
l2 -= 1
77+
else:
78+
if count == 0:
79+
break
80+
else:
81+
l2 -= 1
82+
count -= 1
83+
84+
# compare two pointers
85+
if l1 > -1 and l2 > -1 and s[l1] != t[l2]:
86+
return False
87+
88+
l1 -= 1
89+
l2 -= 1
90+
if l1 == l2:
91+
return True
92+
else:
93+
False

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /