Given an input string (s) and a pattern §, implement regular expression matching with support for ‘.’ and ‘*’.
给定输入字符串和模式(p),实现支持“ . ”和“ * ”的正则表达式匹配。
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
匹配应该覆盖整个输入字符串(而不是部分)。
Note:
s
could be empty and contains only lowercase lettersa-z
.p
could be empty and contains only lowercase lettersa-z
, and characters like.
or*
.- s可以是空的,并且只包含小写字母a-z。
- p可以是空的,并且只包含小写字母a-z和字符 . 和 *。
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Example 5:
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
分析:
用动态规划解决。其中dp[i][j]
表示s[0......i-1]
与p[0......j-1]
是否匹配,若匹配成功则返回true
,不匹配则返回false
。
匹配的原则是2个字符串相等,即s[0.....i-1] == p[0......j-1]
,同时引入2个新字符.
和*
,并且.
和*
只会在字符串p中出现。其中:
.
可以当作任意一个字符来使用。
*
可以让他前面一位的字符使用0到无数次。(比如b*a
等价于 "", "ba" ,"baa", "baaa", "baaaa",······
)
另外可以发现d[i][j]
里表示的字符,在字符串s或p中,下标需要减一,所以引入curP
and curS
方便算清楚下标。
难点在于某些特殊情况的处理,例如字符串abc*d
当p=abc*d
时,
若s=abc
,那么*d
应该计算0次,即空串。dp[i][j] = dp[i][j-2]
若s=abcd
,那么*d
应该计算1次。dp[i][j] = dp[i][j-1]
若s=abcddd
,那么*d
应该计算3次。dp[i][j] = dp[i-1][j]
于是就需要把3种情况都试一遍,即dp[i][j] = dp[i][j-2]|| dp[i][j-1]|| dp[i-1][j];
C++代码
class Solution{
public:
bool isMatch(string s,string p){
int m = s.size();
int n = p.size();
bool dp[m+1][n+1];
memset(dp,0,sizeof(dp));//初始化为false
dp[0][0] = true;//表示空串可以和空串匹配。
for(int j=2;j<=n && p[j-1]=='*';j+=2){//表示若p = #*#*#*可以和空串(s="")匹配
dp[0][j] = true;
}
//dp
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
char curS = s[i-1];//声明curS 和curP 解决下标问题.
char curP = p[j-1];
if(curS == curP || curP == '.'){
dp[i][j] = dp[i-1][j-1];
}
else if( curP == '*'){
char precurP = p[j-2];// precurP 表示'?*'中的字符 "?";
if(precurP != '.' && precurP!=curS){
dp[i][j] = dp[i][j-2];//在这种情况下, *a 数零次
}else{
dp[i][j] = dp[i][j-2]|| //在这种情况下, *a 数零次
dp[i][j-1]|| //在这种情况下, *a 数一次
dp[i-1][j]; //在这种情况下, *a 数许多次
}
}
}
}
return dp[m][n];
}
};