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
Runtime: 56 ms beats 93.00% of java submissions.
public boolean isMatch(String s, String p) {
int i = 0, j = 0, match = 0, star = -1; // i,j分别表示记录s与p的双指针
while (i < s.length()) {
if (j < p.length() && (p.charAt(j) == '?' || s.charAt(i) == p.charAt(j))) {
i++;
j++;
} else if (j < p.length() && p.charAt(j) == '*') { //这里'*'表示0个字符
star = j; // 记录下此时'*'的位置信息,
match = i;//此时对应的s的位置信息i
j++;//继续往后
} else if (star != -1) { // 出现不匹配情况,回溯至'*'继续进行匹配
j = star + 1; // 回溯到前面'*'处,继续进行匹配
i = ++match; // 尝试s向前忽略一位,继续进行匹配
} else return false;// 完全不匹配情况
}
while (j < p.length() && p.charAt(j) == '*') j++;
return j == p.length();
}
参考http://blog.youkuaiyun.com/woliuyunyicai/article/details/49105557
以下是自己的brute force . Runtime: 123 ms beats 27.31% of java submissions.
public boolean isMatch(String ss, String pp) {
if (pp.equals("*")) return true;
int pn = pp.length(), sn = ss.length();
boolean[][] dp = new boolean[sn + 1][pn + 1];
char[] s = ss.toCharArray(), p = pp.toCharArray();
dp[sn][pn] = true;
for (int i = sn; i >= 0; i--)
for (int j = pn - 1; j >= 0; j--)
if (p[j] == '*')
dp[i][j] = dp[i][j + 1] || i < sn && dp[i + 1][j];
else dp[i][j] = i < sn && (p[j] == '?' || s[i] == p[j]) && dp[i + 1][j + 1];
return dp[0][0];
}