-1

我快把头发扯掉了。我花了大约 30 分钟试图解决今天的 leetcode 问题。问题很简单。您将得到两个字符串,S 和 T。# 表示退格。字符串仅包含主题标签和小写字母。检查两个字符串是否相等。(即“#c#d”等于“d”)。这是我的解决方案:

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

有用。你知道什么不起作用吗?r'(.#)'. 为什么?我只是不明白。为什么点不匹配 \w 所做的事情?

具体来说,点在下面失败了,而 \w 没有。

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

返回的点:

S:dfbtu
T:fbtu

w 返回:

S:fbtu
T:fbtu

为什么我的点(应该包含 w)不起作用?先感谢您!

4

1 回答 1

-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
======
于 2020-04-09T12:56:22.987 回答