Description
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)
Example
isMatch(“aa”,”a”) → false isMatch(“aa”,”aa”) → true isMatch(“aaa”,”aa”) → false isMatch(“aa”, “a”) → true isMatch(“aa”, “.”) → true isMatch(“ab”, “.”) → true isMatch(“aab”, “ca*b”) → true
Discussion
这个问题可以采用动态规划。我们维护一个二位数组dp
。dp[i+1][j+1]
记录s[i]
和p[j]
之前的内容是否匹配。下面是dp
的递推式:
dp初始都为0;
- 若p和s当前字符匹配:dp[i + 1][j + 1] = dp[i][j];
若p当前为*,且p前一个字符a和s当前字符a匹配,则a*可以是0,1或n个:dp[i + 1][j + 1] = (dp[i + 1][j - 1] dp[i + 1][j] dp[i][j + 1]); - 若p当前为*,且p前一个字符a和s当前字符b不匹配,则a*只能是0个:dp[i + 1][j + 1] = dp[i + 1][j - 1]。
算法的时间复杂度为O(n^2)。
C++ Code
class Solution {
public:
bool isMatch(string s, string p) {
//由dp[i+1][j+1]来记录s[i]和p[j]之前是否匹配
int dp[s.length() + 1][p.length() + 1];
memset(dp, 0, sizeof(dp));
dp[0][0] = 1;
//考虑a*b*c*开头可能为空的情况
for (int i = 1; i < p.length(); i++)
{
if (p[i] == '*' && dp[0][i-1])
{
dp[0][i+1] = 1;
}
}
for(int i = 0; i < s.length(); i++)
{
for(int j = 0; j < p.length(); j++)
{
//若p和s当前字符匹配
if(p[j] == s[i] || p[j] == '.')
{
dp[i + 1][j + 1] = dp[i][j];
}
//若p当前为*
if(p[j] == '*')
{
//若p前一个字符a和s当前字符a匹配,则a*可以是0,1或n个
if(p[j - 1] == s[i] || p[j - 1] == '.')
{
dp[i + 1][j + 1] = (dp[i + 1][j - 1] || dp[i + 1][j] || dp[i][j + 1]);
}
//若p前一个字符a和s当前字符b不匹配,则a*只能是0个
else
{
dp[i + 1][j + 1] = dp[i + 1][j - 1];
}
}
}
}
return dp[s.length()][p.length()];
}
};