-1

I'm just about done ripping my hair out. I spent about 30 mins trying to solve today's leetcode problem. The problem is simple. You will be given two strings, S and T. # means backspace. The strings contain only hashtags and lowercase letters. Check if the two strings are equal. (i.e. '#c#d' is equal to 'd'). Here is my solution:

import re

class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        while '#' in S or '#' in T:
            S = re.sub(r'(\w#)', r'', S, re.DOTALL)
            T = re.sub(r'(\w#)', r'', T, re.DOTALL)
            if S and S[0] == '#':
                S = S[1:]
            if T and T[0] == '#':
                T = T[1:]
        return S == T

It works. You know what doesn't work? r'(.#)' . Why? I just don't get it. Why won't the dot match things the \w does?

Specifically, the dot failed on the following whereas the \w didn't.

print(backspace_compare("du###vu##v#fbtu", "du###vu##v##fbtu"))

The dot returned:

S:dfbtu
T:fbtu

The w returned:

S:fbtu
T:fbtu

Why didn't my dot, which should encompass w, work? Thank you in advance!

Her0Her0
  • 143
  • 2
  • 9
  • 1
    `.` matches `#` (and backspace, too), and `\w` does not. Probably, you could use `[^#]#` instead. Also, remove `re.DOTALL` or use `flags=re.DOTALL`, you misplaced the argument (or, use the count argument before `re.DOTALL`). See [re.sub with a flag does not replace all occurrences](https://stackoverflow.com/questions/42581). – Wiktor Stribiżew Apr 09 '20 at 12:56

1 Answers1

-1

Because a double backspace will remove two characters. But if you use a dot in your regex, you will also remove a backspace with another backspace and thus might be removing less overall characters than you intended to.

A good way to debug such code is to print intermediate results. Replacing the \w by . will yield

dv#fbtu
dv##fbtu
======
dfbtu
d#fbtu
======
dfbtu
fbtu
======
infinitezero
  • 691
  • 1
  • 6
  • 18