题目描述
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
这个题和前面的Regular Expression Matching差不多,我用了之前的dfs算法,超时了:
public boolean isMatch(String s, String p) {
if(p.length()==0){
return s.length()==0;
}
if(p.charAt(0)=='*'&&s.length()>0){
if(isMatch(s, p.substring(1))){
return true;
}else{
return isMatch(s.substring(1), p);
}
}
if(s.length()==0){
int start=0;
while(start<p.length()&&p.charAt(start)=='*'){
start++;
}
return start==p.length();
}
if(p.charAt(0)=='?'||(s.length()>0&&p.charAt(0)==s.charAt(0))){
return isMatch(s.substring(1), p.substring(1));
}
return false;
}
所以应该想到用动态规划算法,这里的isMatchEmpty(String s)是用来检测s是否能匹配空串,即"****"这样的字符串。
用dp[i][j]来保存s.subString(0,i),与p.subString(0,j)是否匹配。
然后讨论当p.charAt(j)==’*‘,p.charAt(j)==’?‘,p.charAt(j)==s.charAt(i),p.charAt(j)!=s.charAt(i)的情况,注意一些小细节~
代码如下:
public class Solution {
public boolean isMatch(String s, String p) {
if(p.length()==0){
return s.length()==0;
}
if(s.length()==0){
return isMatchEmpty(p);
}
boolean[][] dp=new boolean[s.length()][p.length()];
for(int i=0;i<s.length();i++){
for(int j=0;j<p.length();j++){
if(p.charAt(j)=='*'){
if(i>0){
if(j>0&&dp[i][j-1]){//这个不能掉
dp[i][j]=true;
}else{
dp[i][j]=dp[i-1][j];
}
}else{
if(j==0){
dp[i][j]=true;
}else{
dp[i][j]=dp[0][j-1];
}
}
}else if(p.charAt(j)=='?'||p.charAt(j)==s.charAt(i)){
if(i>0&&j>0){
dp[i][j]=dp[i-1][j-1];
}else if(i==0&&j==0){
dp[i][j]=true;
}else if(i>0&&j==0){
dp[i][j]=false;
}else{
dp[i][j]=isMatchEmpty(p.substring(0,j));
}
}
else{
dp[i][j]=false;
}
}
}
return dp[s.length()-1][p.length()-1];
}
public boolean isMatchEmpty(String s){
int i=0;
while(i<s.length()&&s.charAt(i)=='*'){
i++;
}
return i==s.length();
}
}