Skip to content

Commit 65009b7

Browse files
committed
Create backspace-string-compare.py
1 parent d9f3348 commit 65009b7

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Python/backspace-string-compare.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Time: O(m + n)
2+
# Space: O(1)
3+
4+
# Given two strings S and T, return if they are equal
5+
# when both are typed into empty text editors. # means a backspace character.
6+
#
7+
# Example 1:
8+
#
9+
# Input: S = "ab#c", T = "ad#c"
10+
# Output: true
11+
# Explanation: Both S and T become "ac".
12+
# Example 2:
13+
#
14+
# Input: S = "ab##", T = "c#d#"
15+
# Output: true
16+
# Explanation: Both S and T become "".
17+
# Example 3:
18+
#
19+
# Input: S = "a##c", T = "#a#c"
20+
# Output: true
21+
# Explanation: Both S and T become "c".
22+
# Example 4:
23+
#
24+
# Input: S = "a#c", T = "b"
25+
# Output: false
26+
# Explanation: S becomes "c" while T becomes "b".
27+
#
28+
# Note:
29+
# - 1 <= S.length <= 200
30+
# - 1 <= T.length <= 200
31+
# - S and T only contain lowercase letters and '#' characters.
32+
33+
import itertools
34+
35+
try:
36+
xrange # Python 2
37+
except NameError:
38+
xrange = range # Python 3
39+
40+
41+
class Solution(object):
42+
def backspaceCompare(self, S, T):
43+
"""
44+
:type S: str
45+
:type T: str
46+
:rtype: bool
47+
"""
48+
def findNextChar(S):
49+
skip = 0
50+
for i in reversed(xrange(len(S))):
51+
if S[i] == '#':
52+
skip += 1
53+
elif skip:
54+
skip -= 1
55+
else:
56+
yield S[i]
57+
58+
return all(x == y for x, y in
59+
itertools.izip_longest(findNextChar(S), findNextChar(T)))

0 commit comments

Comments
 (0)