正则表达式匹配
问题链接:https://leetcode-cn.com/problems/regular-expression-matching/
问题描述:给定一个字符串s和字符规律p,实现一个支持’.‘和’*'的正则表达式
- ‘.’:匹配任意单个字符
- ‘*’ 匹配零个或者多个前面的哪一个元素
【python】
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
def matches(i: int, j: int) -> bool:
if i == 0:
return False
if p[j - 1] == '.':
return True
return s[i - 1] == p[j - 1]
f = [[False] * (n + 1) for _ in range(m + 1)]
f[0][0] = True
for i in range(m + 1):
for j in range(1, n + 1):
if p[j - 1] == '*':
f[i][j] |= f[i][j - 2]
if matches(i, j - 1):
f[i][j] |= f[i - 1][j]
else:
if matches(i, j):
f[i][j] |= f[i - 1][j - 1]
return f[m][n]
【JAVA】
public boolean isMatch(String s, String p){
int m = s.length(), n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int i=0; i<=m; i++){
for(int j=1; j<=n; j++){
if (p.charAt(j - 1) == '*'){
dp[i][j] = dp[i][j-2] || dp[i][j];
if (matches(s, p, i, j-1)){
dp[i][j] = dp[i-1][j] || dp[i][j];
}
else{
if (matches(s, p, i, j)){
dp[i][j] = dp[i][j] || dp[i-1][j-1];
}
}
}
}
}
return dp[m][n];
}
public boolean matches(String s, String p, int i, int j){
if (i == 0){
return false;
}
if (p.charAt(j) == '.'){
return true;
}
return s.charAt(i-1) == p.charAt(j-1);
}