1. 程式人生 > 其它 >正則表示式 python

正則表示式 python

實現一個正則表示式匹配,力扣-10

# 給你一個字串 s 和一個字元規律 p,請你來實現一個支援 '.' 和 '*' 的正則表示式匹配。 
#
#
# '.' 匹配任意單個字元
# '*' 匹配零個或多個前面的那一個元素
#
#
# 所謂匹配,是要涵蓋 整個 字串 s的,而不是部分字串。
#
#
# 示例 1:
#
#
# 輸入:s = "aa" p = "a"
# 輸出:false
# 解釋:"a" 無法匹配 "aa" 整個字串。
# .匹配任意單個字元;* 匹配零個或多個前面的那一個元素
def isMatch(s, p):
    result = [[False] * (len(p)+1) for
_ in range(len(s)+1)] # initial stat result[-1][-1] = True # 遞迴遞從後往前匹配 for i in range(len(s), -1, -1): for j in range(len(p)-1, -1, -1): temp = i < len(s) and p[j] in {s[i], '.'} # 在特定長度內,最後一個字元是. if j+1 < len(p) and p[j+1] == '*': # 當前字元的後一個字元是* result[i][j] = result[i][j+2] or
temp and result[i+1][j] else: result[i][j] = temp and result[i+1][j+1] return result[0][0]