Given an input string (s) and a pattern §, implement regular expression matching with support for ‘.’ and ‘*’.
‘.’ 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:
Input:
s = “aa”
p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Example 2:
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:
Input:
s = “ab”
p = “."
Output: true
Explanation: ".” means “zero or more (*) of any character (.)”.
Example 4:
Input:
s = “aab”
p = “cab”
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches “aab”.
Example 5:
Input:
s = “mississippi”
p = “misisp*.”
Output: false
先尝试暴力解法,难点就在 * 身上, * 不会单独出现,它一定是和前面一个字母或".“配成一对。看成一对后"X*”,它的性质就是:要不匹配0个,要不匹配连续的“X”.所以尝试暴力解法的时候一个trick是从后往前匹配.
暴力解法居然也能AC?
是这样来分情况看得:
- 如果s[i] = p[j] 或者 p[j]= . : 往前匹配一位
- 如果p[j] = ’ * ', 检查一下,如果这个时候p[j-1] = . 或者p[j-1] = s[i] ,那么就往前匹配,
- 如果这样能匹配过,就return True(注意如果这样不能最终匹配成功的话我们不能直接返回False,因为还可以直接忽略’ X* '进行一下匹配试试是否可行), 否则我们忽略 ’ X* ',这里注意里面的递推关系
- 再处理一下边界状况:
s已经匹配完了, 如果此时p还有,那么如果剩下的是 X* 这种可以过,所以检查
p匹配完毕,如果s还有那么报错
在这里插入代码片
```class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
def helper(s, i, p, j):
if j == -1:
return i == -1
if i == -1:
if p[j] != '*':
return False
return helper(s, i, p, j-2)
if p[j] == '*':
if p[j-1] == '.' or p[j-1] == s[i]:
if helper(s, i-1, p, j):
return True
return helper(s, i, p, j-2)
if p[j] == '.' or p[j] == s[i]:
return helper(s, i-1, p, j-1)
return False
return helper(s, len(s)-1, p, len(p)-1)