Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created April 5, 2022 21:09
Show Gist options
  • Save les-peters/c83a70bba5b675a65ea5af472295f8c2 to your computer and use it in GitHub Desktop.
Save les-peters/c83a70bba5b675a65ea5af472295f8c2 to your computer and use it in GitHub Desktop.
Equal With Deletions
question = """
Given two strings n and m, return true if they are equal when both are entered into
text editors. But: a # means a backspace character (deleting backwards), and a % means
a delete character (deleting forwards).
Example:
> equalWithDeletions("a##x", "#a#x")
> true // both strings become "x"
> equalWithDeletions("fi##f%%%th %%year #time###", "fifth year time")
> false // the first string becomes "fart"
"""
import re
def equalWithDeletions(n, m):
has_hash_p = re.compile(r'[^#]#')
has_perc_p = re.compile(r'%[^%]')
while has_hash_p.search(n):
n = re.sub(r'[^#]#', '', n)
while has_hash_p.search(m):
m = re.sub(r'[^#]#', '', m)
n = re.sub(r'^#+', '', n)
m = re.sub(r'^#+', '', m)
while has_perc_p.search(n):
n = re.sub(r'%[^%]', '', n)
while has_perc_p.search(m):
m = re.sub(r'%[^%]', '', m)
n = re.sub(r'%+$', '', n)
m = re.sub(r'%+$', '', m)
print(n == m)
equalWithDeletions("a##x", "#a#x")
equalWithDeletions("fi##f%%%th %%year #time###", "fifth year time")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment