两道 hard 的 DP 题,但是理解了就其实不难:
1、LeetCode - 44. Wildcard Matching
2、LeetCode - 10. Regular Expression Matching
LeetCode - 44. Wildcard Matching
Given an input string (\s) and a pattern (\p), implement wildcard pattern matching with support for ‘?’ and ‘*’.
‘?’ Matches any single character.
‘*’ Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
就是 '*'
可以表示空,或者任意长度任意字符串,'?'
可以代表任意一个字符。
用二维矩阵 dp[i][j]
表示 p 前 i 个字符,与 s 前 j 个字符为结尾是否匹配,下图为样例。
bool isMatch(string s, string p) {
const int ls = s.length(), lp = p.length();
vector<vector<bool>> dp(lp + 1, vector<bool>(ls + 1, false));
dp[0][0] = true;
for(int i = 1; i <= lp; ++i) {
const char pch = p[i - 1];
dp[i][0] = dp[i - 1][0] && pch == '*'; // '*':空
for(int j = 1; j <= ls; ++j) {
if (pch == '*')
dp[i][j] = dp[i][j - 1] || dp[i - 1][j] || dp[i - 1][j - 1];
else if (pch == '?' || pch == s[j - 1])
dp[i][j] = dp[i - 1][j - 1];
}
}
return dp[lp][ls];
}
可以看到如果 p[i] 为 '*'
,那么如果 dp[i + 1][j]
为 true,那么后边的所有都为 true(因为 '*'
可以表示任意长度,即直接匹配到最后,如上图第三行)。
当 p[i] 为 '*'
时,有三种情况:
1、'*'
用作表示一个字符:也就是 dp[i - 1][j - 1]
;
2、'*'
用作表示 空:也就是 dp[i - 1][j]
;
3、'*'
用作表示多个字符,也就是前边是 true,后边都是 true,也就是 dp[i][j - 1]
。
其实第一种 dp[i - 1][j - 1]
可以省略,因为 dp[i - 1][j - 1]
为 true 的话,dp[i][j - 1]
肯定有一个是 true。
LeetCode - 10. Regular Expression Matching
Given an input string (s) and a pattern (p), implement regular expression matching with support for ‘.’ and ‘*’.
‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.
就是 '.'
和上边的 '?'
一样,匹配一个任意字符,'*'
表示前边的字符重复任意次(可以 0 次),.*
表示任意长度的任意字符,也就是任意字符串。值得注意的是:p 第一个字符一定不是 '*'
,因为前边没有东西可以重复;且不会有两个连续的 '*'
。
依然是二维矩阵,表示的意思也和上边一样,只是判断条件不一样了,如下图为例。
bool isMatch(string s, string p) {
const int ls = s.length(), lp = p.length();
vector<vector<bool>> dp(lp + 1, vector<bool>(ls + 1, false));
dp[0][0] = true;
for (int i = 1; i <= lp; ++i) {
const char pch = p[i - 1];
if(pch == '*')
dp[i][0] = dp[i - 2][0]; // '*':前边字符重复0次
for (int j = 1; j <= ls; ++j) {
if (pch == '*') {
if (p[i - 2] == '.' || p[i - 2] == s[j - 1])
dp[i][j] = dp[i][j - 1] || dp[i - 1][j] || dp[i - 2][j]; // 重复或不重复
else
dp[i][j] = dp[i - 2][j]; // 重复0次
}
else if (pch == '.' || pch == s[j - 1])
dp[i][j] = dp[i - 1][j - 1];
}
}
return dp[lp][ls];
}