public class WildcardMatching {
public static boolean wm(String s, String p) {
if (p == null || p.length() == 0 || s == null || s.length() == 0) {
return false;
}
char[] pc = p.toCharArray();
char[] sc = s.toCharArray();
boolean dp[][] = new boolean[p.length()+1][s.length()+1];
dp[0][0] = true;
for (int i = 1; i <= p.length(); i++) {
for (int j = 1; j <= s.length();j++){
if (!dp[i-1][j-1]) {
dp[i][j] = false;
continue;
}
if (pc[i-1] == '?') {
dp[i][j] = dp[i-1][j-1];
} else if (pc[i-1] == '*') {
dp[i][j-1] = true;
while (j <= s.length()) {
dp[i][j++] = true;
}
} else if (pc[i-1] == sc[j-1]) {
dp[i][j] = dp[i-1][j-1];
}
}
}
return dp[p.length()][s.length()];
}
public static void main(String[] args) {
System.out.println("TRUE CASES:");
System.out.println(wm("aa", "*"));
System.out.println(wm("cb", "?*"));
System.out.println(wm("acb", "?*"));
System.out.println(wm("aasdf", "?*"));
System.out.println(wm("aassff", "a?*f"));
System.out.println(wm("aassff", "a?*s?*f"));
System.out.println("FALSE CASES: ");
System.out.println(wm("aa", "a"));
System.out.println(wm("cb", "?a"));
System.out.println(wm("aassff", "a?*b"));
System.out.println();
}
}
解题思路:
与正则匹配思路基本一致,不同点在于此题的 '*' ,可以与空匹配, 即 输入串s[1,j] 与 pattern串 p[1,i] 匹配的话, 如果i+1位置为'*', 那么s[1,j] 也与 p[1,i+1] 匹配