正则表达式匹配

请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     # s, pattern都是字符串
 4     def match(self, s, pattern):
 5         m,n = len(s),len(pattern)
 6         dp = [[False for _ in range(n+1)]for _ in range(m+1)]
 7         dp[0][0] = True
 8         for i in range(1,n+1):
 9             if (pattern[i-1] == '*'):
10                 dp[0][i] = dp[0][i-2]
11         for i in range(1,m+1):
12             for j in range(1,n+1):
13                 if s[i-1] == pattern[j-1] or pattern[j-1] == '.':
14                     dp[i][j] = dp[i-1][j-1]
15                 elif pattern[j-1] == '*':
16                     if pattern[j-2] == s[i-1] or pattern[j-2] == '.':
17                         dp[i][j] |= dp[i][j-1]
18                         dp[i][j] |= dp[i-1][j]
19                         dp[i][j] |= dp[i][j-2]
20                     else:
21                         dp[i][j] = dp[i][j-2]
22         return dp[m][n]
23         # write code here

 

posted on 2019-06-14 08:43  Sempron2800+  阅读(125)  评论(0编辑  收藏  举报