此题有待深究 哦哦哦
题目描述
自己的思路:
- 由于*控制的是其前面字符的匹配,因此可以由正则表达式的末尾开始检查;
- 没了。。没了。。。直接用字符串的方法肯定是不行的,越想越复杂。。
↓↓别人的思路
If you are stuck, recursion is your friend.
递归
这个代码还没调通,递归调用函数出错,作用域问题
1 | class Solution: |
动态规划
This problem has a typical solution using Dynamic Programming. We define the state P[i][j] to be true if s[0..i) matches p[0..j) and false otherwise. Then the state equations are:
a. P[i][j] = P[i - 1][j - 1], if p[j - 1] != ‘’ && (s[i - 1] == p[j - 1] || p[j - 1] == ‘.’);
b. P[i][j] = P[i][j - 2], if p[j - 1] == ‘’ and the pattern repeats for 0 times;
c. P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == ‘.’), if p[j - 1] == ‘*’ and the pattern repeats for at least 1 times.
Putting these together, we will have the following code.
1 | class Solution: |
使用第三方库re
一行代码/微笑脸1
2
3
4
5import re
class Solution:
def isMatch(self, s, p):
return re.match('^' + p + '$', s) != None
