这题的dp和第10题的solution类似。
第10题的dp
http://www.cnblogs.com/grandyang/p/4461713.html
Solution 1:dp
这里dp的涵义和第10题一样
class Solution {
public boolean isMatch(String s, String p) {
if(s==null || p==null) return false;
int s_len = s.length();
int p_len = p.length();
boolean[][] d = new boolean[s_len+1][p_len+1];
d[0][0] = true;
//初始化,s为空的时候,出现*的情况,*前必须也true,*这里才能true
for (int i = 1; i <= p_len; i++) {
if ( p.charAt(i-1) == '*') d[0][i] = d[0][i-1];
}
for (int i = 1; i <= s_len; i++) {
for (int j = 1; j <= p_len; j++) {
if(p.charAt(j-1) == '?') d[i][j] = d[i-1][j-1];
if(p.charAt(j-1) == s.charAt(i-1)) d[i][j] = d[i-1][j-1];
if(p.charAt(j-1) == '*') d[i][j] = d[i][j-1] || d[i-1][j];
// *为空 //*匹配了一个或多个
}
}
return d[s_len][p_len];
}
}
Solution 2:回溯法
个人觉得不大好理解,我也写不出来
在这里插入代码片
> s: abcded
p: a*df
as we can see first we meet " * ", p = 1, star = 1, and match = 1, s = 1;
then p= 2 and he will be waiting there......and when s = 3 we have a match, great ! Then p = 3, s = 4, then they do not match ,so sad!
so p will go back to "p = 2"(he will be waiting for a while ) and as we have "match = 3" and match++, so now match = 4, does not match , then match = 5, also s = 5, match again!!
so in my opinion , the global variable "match " is to store the last index in "s" when we meet star in "p", because as you can see from my example even though we can match later , but that does not mean the current substring is the right answer , "match" give us a chance to move on and visit more characters in s ....hope that helps!
boolean comparison(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++;
}
// staridx记最近出现的*的位子,p是*后的元素,p在这里等着
else if (p < pattern.length() && pattern.charAt(p) == '*'){
starIdx = p;
match = s;
p++;
}
// 如果不匹配,在p回到最近的一次*的后面一个,s和match前进
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();
}