您的位置:首页 > 其它

LeetCode_OJ【44】Wildcard Matching

2016-01-14 17:34 495 查看
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

本题给的提示是动态规划,回溯,贪心

一开始我只用回溯求解,写出如下算法:

public class Solution {
public boolean isMatch(String s, String p) {
if(p.length() == 0 || s.length() == 0)
return p.length() == 0 && s.length() == 0;
else if(p.charAt(0) == '*'){
while(p.length() > 1 && p.charAt(1) == '*')
p = p.substring(1);
if(isMatch(s, p.substring(1)))
return true;
else
return isMatch(s.substring(1), p);
}
else if(p.charAt(0) == '?' || p.charAt(0) == s.charAt(0)){
return isMatch(s.substring(1), p.substring(1));
}
else
return false;
}
}


结果很多用例过不去。只用回溯的话,时间复杂度确实太高了,碰到稍长一点的字符串就需要很长的时间才跑出结果(我给没通过的例子在自己的机器上面跑了下,几分钟都没出结果)。

然后就想了下用动规应该怎么解,其实能写出回溯的算法基本就已经完成了一大半了。

这里使用一个二维数组记录s的子串和p的子串的匹配情况,res[0][0]表示s和p都匹配完了,所以为true;

res[o][j]表示p串匹配完了,s串还剩j个字符,res[i][0]表示s匹配完了,p还剩i个字符,初始化的时候可以得到这些数据。

后面可以根据回溯算法的求解过程依次求出res[i][j]。最后res[p.length()][s.length()]就是最终结果。

下面是该思路的JAVA实现。

public class Solution {
public boolean isMatch(String s, String p) {
boolean[][] res =new boolean[p.length()+1][s.length()+1];
res[0][0] = true;
for(int j = 1 ; j < s.length() +1 ; j ++){
res[0][j] = false;
}
for(int i = 1 ; i < p.length() +1 ; i ++){
if(res[i-1][0] == true && p.charAt(p.length() - i) == '*')
res[i][0] = true;
else
res[i][0] =false;
}
for(int i = 1 ; i < p.length() +1; i ++){
for(int j = 1; j < s.length() +1; j ++){
if(p.charAt(p.length() - i) == '*'){
res[i][j] = res[i -1][j] == true ? true : res[i][j-1];
}
else if(p.charAt(p.length() -i) == '?' || p.charAt(p.length() -i) == s.charAt(s.length() -j))
res[i][j] = res[i-1][j-1];
else
res[i][j] = false;
}
}
return res[p.length()][s.length()];

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 回溯 DP