# [leetcode] 44. 通配符匹配(Java)(动态规划)

44. 通配符匹配

'' , 即可以代替0个、1个或者多个，对于的状态f[i][j]可以由f[i-1][j-1]，f[i][j-1]和f[i-1][j]而来，即f[i][j] = f[i - 1][j - 1] || f[i - 1][j] || f[i][j - 1];

if (p.length() > 0 && p.charAt(0) == '
') {
f[0][1] = true;
}

class Solution {
public boolean isMatch(String s, String p) {
String tp = "";

//处理p中多余的*
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '*') {
tp += '*';
while (i < p.length() && p.charAt(i) == '*') i++;
}
if (i < p.length()) {
tp += p.charAt(i);
}
}
p = tp;

boolean[][] f = new boolean[s.length() + 1][p.length() + 1];
f[0][0] = true;

// 注意，当p以*开头时
if (p.length() > 0 && p.charAt(0) == '*') {
f[0][1] = true;
}

for (int i = 1; i <= s.length(); i++) {
for (int j = 1; j <= p.length(); j++) {
if (p.charAt(j - 1) == '*') {
f[i][j] = f[i - 1][j - 1] || f[i - 1][j] || f[i][j - 1];
} else {
f[i][j] = f[i - 1][j - 1] && (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '?');
}
}
}

return f[s.length()][p.length()];
}
}

posted @ 2018-07-21 13:32  ACBingo  阅读(1268)  评论(0编辑  收藏