【发布时间】:2015-12-08 20:05:43
【问题描述】:
解决以下模式匹配问题。并发布详细的问题陈述和代码。代码正在运行。在下面的实现中,它在外循环中循环查找模式,然后在内部循环匹配源字符串——以构建二维 DP 表。
我的问题是,如果我更改实现,哪个外部循环用于匹配源字符串,而内部循环用于模式。是否会有任何性能提升或任何功能缺陷?任何关于哪种口味更好或几乎相同的建议都值得赞赏。
更具体地说,我的意思是从下面更改循环(对循环的内容使用类似的逻辑),
for i in range(1, len(p) + 1):
for j in range(1, len(s) + 1):
到,
for i in range(1, len(s) + 1):
for j in range(1, len(p) + 1):
问题陈述
'.'匹配任何单个字符。
'*' 匹配零个或多个前面的元素。匹配应该覆盖整个输入字符串(不是部分)。
函数原型应该是:
bool isMatch(const char *s, const char *p)一些例子:
isMatch("aa","a") → 假
isMatch("aa","aa") → 真
isMatch("aaa","aa") → 假
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
class Solution(object):
def isMatch(self, s, p):
# The DP table and the string s and p use the same indexes i and j, but
# table[i][j] means the match status between p[:i] and s[:j], i.e.
# table[0][0] means the match status of two empty strings, and
# table[1][1] means the match status of p[0] and s[0]. Therefore, when
# refering to the i-th and the j-th characters of p and s for updating
# table[i][j], we use p[i - 1] and s[j - 1].
# Initialize the table with False. The first row is satisfied.
table = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]
# Update the corner case of matching two empty strings.
table[0][0] = True
# Update the corner case of when s is an empty string but p is not.
# Since each '*' can eliminate the charter before it, the table is
# vertically updated by the one before previous. [test_symbol_0]
for i in range(2, len(p) + 1):
table[i][0] = table[i - 2][0] and p[i - 1] == '*'
for i in range(1, len(p) + 1):
for j in range(1, len(s) + 1):
if p[i - 1] != "*":
# Update the table by referring the diagonal element.
table[i][j] = table[i - 1][j - 1] and \
(p[i - 1] == s[j - 1] or p[i - 1] == '.')
else:
# Eliminations (referring to the vertical element)
# Either refer to the one before previous or the previous.
# I.e. * eliminate the previous or count the previous.
# [test_symbol_1]
table[i][j] = table[i - 2][j] or table[i - 1][j]
# Propagations (referring to the horizontal element)
# If p's previous one is equal to the current s, with
# helps of *, the status can be propagated from the left.
# [test_symbol_2]
if p[i - 2] == s[j - 1] or p[i - 2] == '.':
table[i][j] |= table[i][j - 1]
return table[-1][-1]
提前致谢, 林
【问题讨论】:
-
你为什么不用正则表达式?
-
@deloz,这只是一个 DP 编程难题。感谢您对我最初的问题的建议。 :)