题解 | #字符串通配符#

字符串通配符

https://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036

import sys


# dp[i][j] 代表pattern[0:i-1]是否匹配word[0:j-1]
# if pattern[i-1] != ?* dp[i][j]=dp[i-1][j-1] and pattern[i-1]== word[j-1]
# if pattern[i-1] == ?
# if pattern[i-1] == * dp[i][j] =dp[i-1][j] or dp[i-1][j-1] or dp[i-1][j-2] or ... or
pattern, word = input().lower(), input().lower()
p_len, w_len = list(map(len, [pattern, word]))


dp = [[False] * (w_len + 1) for i in range(p_len + 1)]
dp[0][0] = True
for i in range(1, w_len + 1):
    dp[0][i] = False
for i in range(1, p_len + 1):
    dp[i][0] = pattern[0:i].count("*") == i

last_bool = [False] * (w_len + 1)
last_bool[0] = dp[0][0]
# last_bool[j]会等于dp[i-1][j] or dp[i-1][j-1] or dp[i-1][j-2] ... or dp[i-1][0]
for i in range(1, w_len + 1):
    last_bool[i] = last_bool[i - 1] or dp[0][i]
for i in range(1, p_len + 1):
    last_bool[0] = dp[i][0]
    for j in range(1, w_len + 1):
        #print(i, j)
        if pattern[i - 1] == "?":
            if not (word[j - 1].isdigit() or word[j - 1].isalpha()):
                dp[i][j] = False
            else: dp[i][j]=dp[i-1][j-1]
        elif pattern[i - 1] == "*":
            if not (word[j - 1].isdigit() or word[j - 1].isalpha()):
                dp[i][j] = dp[i - 1][j]
            else: dp[i][j] = last_bool[j]
        else:
            dp[i][j] = dp[i - 1][j - 1] and pattern[i - 1] ==  word[j - 1]
        #print(dp[i][j])
        last_bool[j] = last_bool[j - 1] or dp[i][j]

print(str(dp[p_len][w_len]).lower())


"""?*bc*?
abcd"""

"""a*?*c
a@c"""

全部评论

相关推荐

10-28 15:45
门头沟学院 C++
西南山:海康威视之前不是大规模裁员吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务