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
解题思路: 采用动态规划,match[i][j]和之前的匹配结果相关,当考虑match[i][j]时的取值时,应该分p字符串第j个字符是不是'*',若是,则又要分为'*'前面的字符匹配0次和匹配一次及以上的情况,
时间和空间复杂度均为O(M*N)
<span style="font-size:14px;">public boolean isMatch(String s, String p) {
if(p.isEmpty())
return s.isEmpty();
if(p.charAt(0)=='*')
return false;
int len1=s.length(),len2=p.length();
int i=0,j=0;
boolean[][] match=new boolean[len1+1][len2+1];
match[0][0]=true;
for(i=1;i<=len1;i++)
match[i][0]=false;
match[0][1]=false;
for(i=2;i<=len2;i++){
if(p.charAt(i-1)=='*')
match[0][i]=match[0][i-2];
else
match[0][i]=false;
}
for(i=1;i<=len1;i++){
for(j=1;j<=len2;j++){
if(p.charAt(j-1)=='*')
match[i][j]=match[i][j-2]||((p.charAt(j-2)=='.'||p.charAt(j-2)==s.charAt(i-1))&&match[i-1][j]);
else
match[i][j]=match[i-1][j-1]&&(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i-1));
}
}
return match[len1][len2];
}</span>
44. Wildcard Matching
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).
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", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
思路: 和上面正则式匹配一样的道理,都是动态规划问题.但这里"*"是匹配任意字符,所以这个应该从后往前推.
时间复杂度:O(M*N)
空间复杂度; O(M*N)
public boolean isMatch(String s, String p) {
int len1=s.length(),len2=p.length();
boolean[][] flag=new boolean[len1+1][len2+1];
flag[len1][len2]=true;
int i=len2-1;
for(;i>=0;i--){
if(p.charAt(i)=='*')
flag[len1][i]=true;
else
break;
}
while(i>=0)
flag[len1][i--]=false;
for(i=0;i<len1;i++)
flag[i][len2]=false;
for(i=len1-1;i>=0;i--){
for(int j=len2-1;j>=0;j--){
if(p.charAt(j)=='*'){
flag[i][j]=flag[i][j+1]||flag[i+1][j];
}else{
if(p.charAt(j)=='?')
flag[i][j]=flag[i+1][j+1];
else
flag[i][j]=(s.charAt(i)==p.charAt(j))&&flag[i+1][j+1];
}
}
}
return flag[0][0];
}