10. Regular Expression Matching

2019-03-28

10. Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

1
2
'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

1
2
3
4
5
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

1
2
3
4
5
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

1
2
3
4
5
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

1
2
3
4
5
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

1
2
3
4
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
# @return a boolean
def isMatch(self, s, p):
# dp[len(s)+1][len(p)+1] 从1开始存数据 dp[0][0]作为True 其他默认为F
dp=[[False for i in range(len(p)+1)] for j in range(len(s)+1)]
dp[0][0]=True
for i in range(1,len(p)+1):
if p[i-1]=='*' and i>=2:
dp[0][i]=dp[0][i-2]
for i in range(1,len(s)+1):
for j in range(1,len(p)+1):
if p[j-1]=='.':
dp[i][j]=dp[i-1][j-1]
elif p[j-1]=='*':
dp[i][j]=dp[i][j-1] or dp[i][j-2] or (dp[i-1][j] and (s[i-1]==p[j-2] or p[j-2]=='.'))
else:
dp[i][j]=dp[i-1][j-1] and s[i-1]==p[j-1]
return dp[len(s)][len(p)]
# 找'*'在p[j-1]则 dp[0][i]=dp[0][i-2]
# 1.找'.'在p[j-1]则 dp[i][j]=dp[i-1][j-1]
# 2.无'.'找'*'在p[j-1] 对'*'代表数字进行讨论
# 2.1 代表0个 则dp[i][j] = dp[i][j-2]
# 2.2 代表1个 则dp[i][j] = dp[i][j-1]
# 2.3 代表More个 则dp[i][j] = dp[i-1][j] and(s[i-1]==p[j-2] orp[j-2]='.')

Re-Code:

1
2
3
4
5
6
import re

class Solution:
# @return a boolean
def isMatch(self, s, p):
return re.match('^' + p + '$', s) != None
-->