思路:考虑动态规划,dp[][]矩阵表示s与p部分字符串是否匹配。
- 第一行,当p中为‘ * ’ 时,match[0][i]=match[0][i-2];
- 当p中为’ . '或p中字符等于s中字符时,match[si][pi]=match[si-1][pi-1];
- 当p中为’ * '时,
(1) 若 ’ * ‘前面的字符等于s中字符,或’ * ‘前面的字符为’ .’ ,则match[si][pi]=match[si][pi-2] || match[si-1][pi];
(2) 否则,match[si][pi]=match[si][pi-2];
最后返回矩阵最右下角的数match[s.length()][p.length()]
class Solution {
public boolean isMatch(String s, String p) {
if(s==null || p==null){
return false;
}
boolean[][] match=new boolean[s.length()+1][p.length()+1];//boolean声明的时候默认都是false
match[0][0]=true;
for(int i=1;i<=p.length();i++){
if(p.charAt(i-1)=='*'){
match[0][i]=match[0][i-2];
}
}
for(int si=1;si<=s.length();si++){
for(int pi=1;pi<=p.length();pi++){
if(p.charAt(pi-1)=='.' || p.charAt(pi-1)==s.charAt(si-1)){
match[si][pi]=match[si-1][pi-1];
}
else if(p.charAt(pi-1)=='*' ){
if(p.charAt(pi-2)==s.charAt(si-1) || p.charAt(pi-2)=='.'){
match[si][pi]=match[si][pi-2] || match[si-1][pi];
}
else{
match[si][pi]=match[si][pi-2];
}
}
}
}
return match[s.length()][p.length()];
}
}