Created
April 9, 2020 08:33
-
-
Save alxfv/0811886b3f3a6877ca47837b5ff5d8ca to your computer and use it in GitHub Desktop.
Backspace String Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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