Last active
April 9, 2020 09:06
-
-
Save alxfv/1b93ac55d183c42a6fd7c07628057219 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, *all_strings) -> bool: | |
def next_index(s: 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 # we need next index - so let's move | |
backspaces = 0 | |
# trying to find next undeleted letter | |
while i >= 0 and not (s[i] != '#' and backspaces == 0): | |
if s[i] == '#': | |
backspaces += 1 | |
else: | |
backspaces -= 1 | |
i -= 1 | |
return i | |
indices = [len(R) for R in all_strings] | |
first_string = all_strings[0] | |
while True: | |
# next letter indices | |
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