String Comparison
June 21, 2019
We assume the strings are well-formed, with no backspaces that back up the string past its beginning. First we clean
the strings to remove all backspace characters and the characters they render invisible:
(define (clean str) (let loop ((xs (string->list str)) (zs (list))) (cond ((null? xs) (list->string (reverse zs))) ((char=? (car xs) #\#) (loop (cdr xs) (cdr zs))) (else (loop (cdr xs) (cons (car xs) zs))))))
Then we compare the cleaned strings:
(define (comp s1 s2) (string=? (clean s1) (clean s2)))
Here’s an example:
> (clean "abcx#de") "abcde" > (comp "abcx#de" "abcde") #t
My first attempt to write this function failed. I kept the strings as strings, used indexes to point to the characters in the strings, and compared the strings at the same time I was backspacing through the removed characters. It was a mess. Separating clean
from comp
makes the task simpler and the code easier to read.
You can run the program at https://ideone.com/ip8mAg.
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: