Skip to content

Instantly share code, notes, and snippets.

@alxfv
Created April 9, 2020 08:33
Show Gist options
  • Save alxfv/0811886b3f3a6877ca47837b5ff5d8ca to your computer and use it in GitHub Desktop.
Save alxfv/0811886b3f3a6877ca47837b5ff5d8ca to your computer and use it in GitHub Desktop.
Backspace String Compare
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
def next_index(R: str, i: int) -> int:
"""
Get the index of the next undeleted letter
@param R: str string
@param i: index
@return: current letter index
"""
i -= 1
k = 0 # backspace
while i >= 0 and not (R[i] != '#' and k == 0):
if R[i] == '#':
k += 1
else:
k -= 1
i -= 1
# no more letters left
return i
all_strings = [S, T] # array of strings
indices = [len(R) for R in all_strings]
first_string = all_strings[0]
while True:
# next indices to compare of all strings
next_indices = list(map(next_index, all_strings, indices))
# if we are out of range in all strings - all strings are equal
if all(j == -1 for j in next_indices):
return True
# if we are out of range only in some of the strings - they are not equal
if any(j == -1 for j in next_indices):
return False
# a current letter in the first string
c = first_string[next_indices[0]]
# i - a string index, j - a letter index in a string
for i, j in enumerate(next_indices):
if c != all_strings[i][j]:
return False
indices = next_indices
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment