String Comparison
June 21, 2019
A string is a sequence of characters, perhaps including a backspace character that renders both itself and the previous character as if they were not part of the string. For instance, if we make the backspace character visible using the #
symbol, the two strings abcx#de
and abcde
are identical. Multiple successive backspaces remove multiple successive characters.
Your task is to write a program that compares two strings that may contain backspaces and reports if they are equal. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
A Haskell version.
https://pastebin.com/31W4AtR2
#https://programmingpraxis.com/2019/06/21/string-comparison/
def clean(word):
for i in word:
if i == ‘#’:
if word.index(i) == 0:
word = word[1:]
else:
word = word[0:word.index(i)-1] + word[word.index(i)+1:]
return word
def hashCompare(word1,word2):
word2 = clean(word2)
word1 = clean(word1)
if word1 == word2:
return True
else:
return False
print(str(hashCompare("abcde","abcx#de"))) #true
print(str(hashCompare("#abc##","1#234###a"))) #true
print(str(hashCompare("ab","aa"))) #false
In Python.
In Rust
Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d73ac79321dbff905a6105f6ead4754d
Rust V2
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=14beb8ac709eff1e1dfce4b8ca521486
Here’s a solution in C.
Example Usage:
Here’s another solution in C.
This approach modifies the strings in-place, then compares.
Example Usage: