class Solution {
public static void main(String[] args) {
Solution s=new Solution();
boolean res=s.isMatch("aa","*");
System.out.println(res);
}
public boolean isMatch(String s, String p) {
boolean[][] match=new boolean[p.length()+1][s.length()+1];
for(int i=0;i<p.length()+1;i++)
{
for(int j=0;j<s.length()+1;j++)
{
match[i][j]=false;
}
}
match[0][0]=true;
for(int i=0;i<p.length();i++)
{
if(p.charAt(i) == '*')
match[i+1][0] = match[i][0];
}
for(int i=0;i<p.length();i++)
{
for(int j=0;j<s.length();j++)
{
if(p.charAt(i)==s.charAt(j)||p.charAt(i)=='?')
{
match[i+1][j+1]=match[i][j];
}
else if(p.charAt(i)=='*')
{
match[i+1][j+1]=match[i+1][j]||match[i][j+1];
}
}
}
return match[p.length()][s.length()];
}
}
这题和leetcode 10很像 都可以用动态规划做,不同的是在 p.charAt(i)==’*'时可以简化
为什么可以把思路二中的f(x, y) = f(x-1, y ) || f(x - 1, y - 1) || f(x - 1, y -2) || … || f(x-1, 0)简化为f(x, y) = f(x-1, y 1) || f(x - 1, y)呢?因为一旦f(x - 1, y - 1) || f(x - 1, y -2) || … || f(x-1, 0)中有一项成立即会导致f(x - 1, y)成立,即其中所有的从差值字符都可以被‘ * ’替代