题目描述:
思路:理解错了题意中的*的作用,题目中*的作用是表示零个或多个前一个字符,而自己理解成了任意数量的任意字符。
理解错误的代码:(之所以用m+1和n+1是为了方便第一行第一列的初始化)
class Solution {
public boolean isMatch(String s, String p) {
int m=s.length();
int n=p.length();
boolean[][] result=new boolean[n+1][m+1];
result[0][0]=true;
for (int i=1;i<=n;i++){
for (int j=i;j<=m;j++){
if ((p.charAt(i-1)>='a')&&(p.charAt(i-1)<='z')){//p为字母
if (p.charAt(i-1)==s.charAt(j-1)){
result[i][j]=result[i-1][j-1];
}//不等时候初始化就是false不用改变
}else if (p.charAt(i-1)=='.'){
result[i][j]=result[i-1][j-1];
}else {//p是*
if (result[i-1][j-1]){
result[i][j]=true;
}else {
result[i][j]=result[i][j-1];
}
}
}
}
return result[n][m];
}
}
那么如何改进呢,只需要在p的字符是*时候来改进即可。(忙乎了好几个点发现题意理解错误。。完全莫得心情去改正了。。)
附上官方的解答吧:(具体思路请参考leetcode官方题解)
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean[][] f = new boolean[m + 1][n + 1];
f[0][0] = true;
for (int i = 0; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (p.charAt(j - 1) == '*') {
f[i][j] = f[i][j - 2];
if (matches(s, p, i, j - 1)) {
f[i][j] = f[i][j] || f[i - 1][j];
}
}
else {
if (matches(s, p, i, j)) {
f[i][j] = f[i - 1][j - 1];
}
}
}
}
return f[m][n];
}
public boolean matches(String s, String p, int i, int j) {
if (i == 0) {
return false;
}
if (p.charAt(j - 1) == '.') {
return true;
}
return s.charAt(i - 1) == p.charAt(j - 1);
}
}