Implement wildcard pattern matching with support for '?'
and '*'
.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
在这里,需要实现2种通配符, ' ? ' 和 ' * ',其中?可以匹配任意的字符, * 可以匹配0到多个字符。
我们假设有一个ismatch[ i ] [ j ] 表示,s [ 0... i ] 与 s[ 0 ...j ] 的匹配情况。ismatch[ 0 ] [ 0 ] 表示S为空,且P为空,此时ismatch[ 0 ][ 0 ] = true。
下面来考虑general的情况。
如果我们已经计算了ismatch[ i - 1][ j - 1],
那么如果p[ j - 1] != ' * ' :
但前面的ismatch[ i - 1] p [ j - 1] = true 且,p[ j - 1] == '? 或者s[ j - 1] == p [ j - 1]匹配的话,0...i 与 0...j也是匹配的了。
如果p [ j - 1] == ' * ':
那么我们看ismatch[ i ][ p -1] (此时* 表示匹配zero sequence) 和 ismatch[ i - 1] [ p ] 的值 (此时*匹配了s[ i - 1] )。
对于base case的讨论,当 i = 0的时候,j !=0 的时候,p需要* 才能实现匹配。
当 i != 0, 当 j = 0的时候,都无法匹配。
代码:
public class WildcardMatching {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
boolean[][] ismatch = new boolean[m + 1][n + 1];
ismatch[0][0] = true;
for (int j = 1; j <= n; j++) {
ismatch[0][j] = ismatch[0][j - 1] && p.charAt(j - 1) == '*';
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '*') {
ismatch[i][j] = ismatch[i][j - 1] || ismatch[i - 1][j];
}
else {
ismatch[i][j] = ismatch[i - 1][j - 1] && (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '?');
}
}
}
return ismatch[m][n];
}
}