题目
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).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
答案
几乎跟Regular Expression Matching这题是一样的,只是需要根据题目要求修改一下recurrence 的公式
class Solution {
public boolean isMatch(String s, String p) {
int s_len = s.length(), p_len = p.length();
boolean[][] dp = new boolean[s_len + 1][p_len + 1];
// Empty text matches empty empty pattern
dp[0][0] = true;
for(int i = 1; i <= s_len; i++)
dp[i][0] = false;
for(int j = 1; j <= p_len; j++) {
char pattern_c = p.charAt(j - 1);
if(pattern_c == '*') {
dp[0][j] = dp[0][j - 1];
}
else {
dp[0][j] = false;
}
}
for(int i = 1; i <= s_len; i++) {
for(int j = 1; j <= p_len; j++) {
char pattern_c = p.charAt(j - 1);
if(pattern_c == '*') {
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
else if(pattern_c == '?' || pattern_c == s.charAt(i - 1)) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[s_len][p_len];
}
}