您的位置:首页 > 其它

leetcode 44. Wildcard Matching

2017-06-05 01:32 369 查看
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


Subscribe to see which companies asked this question.
又是一道正则匹配的问题,这次用的是非dp的思路,如果s和p的每一位是一一对应的(包括?)则去匹配下一位,如果p是*,那么就去匹配s和p+1,如果匹配失败则回退,s++。

public class Solution {
public boolean isMatch(String str, String pattern) {
int s = 0, p = 0, match = 0, starIdx = -1;
while (s < str.length()){
// advancing both pointers
if (p < pattern.length()  && (pattern.charAt(p) == '?' || str.charAt(s) == pattern.charAt(p))){
s++;
p++;
}
// * found, only advancing pattern pointer
else if (p < pattern.length() && pattern.charAt(p) == '*'){
starIdx = p;
match = s;
p++;
}
// last pattern pointer was *, advancing string pointer
else if (starIdx != -1){
p = starIdx + 1;
match++;
s = match;
}
//current pattern pointer is not star, last patter pointer was not *
//characters do not match
else return false;
}

//check for remaining characters in pattern
while (p < pattern.length() && pattern.charAt(p) == '*')
p++;

return p == pattern.length();
}
}
补充一种dp方法:

public class Solution {
public boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int j = 1; j <= n; j++)
dp[0][j] = dp[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) == s.charAt(i - 1) || p.charAt(j - 1) == '?')
dp[i][j] = dp[i - 1][j - 1];
else if(p.charAt(j - 1) == '*')
dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
}
}
return dp[m]
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: