Implement wildcard pattern matching with support for ‘?’ and ‘*’.
题意
和LeetCode-10. Regular Expression Matching很像的一道题,不同之处在于本题的’?’对应到了之前的’.’,‘*’的作用也改变了。
分析
唯一不同的在于如果‘*’之前就不匹配那么后面也就不匹配了,即递推式有所改变。
Java动态规划解法
class Solution {
public boolean isMatch(String s, String p) {
if(s==null||p==null)
return false;
boolean[][] dp=new boolean[s.length()+1][p.length()+1];
dp[0][0]=true;
for(int j=0;j<p.length();++j)
{
if(p.charAt(j)=='*'&&dp[0][j])
dp[0][j+1]=true;
}
for(int i=0;i<s.length();++i)
{
for(int j=0;j<p.length();++j)
{
if(p.charAt(j)==s.charAt(i)||p.charAt(j)=='?')
dp[i+1][j+1]=dp[i][j];
if(p.charAt(j)=='*')
dp[i+1][j+1]=dp[i+1][j]||dp[i][j+1];
}
}
return dp[s.length()][p.length()];
}
}