Implement regular expression matching with support for '.'
and '*'
.
'.' Matches any single character. '*' Matches zero or more of the preceding element. 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", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true
这是一道很难, 也是我比较怕的题目, 今天(11/1)还算没有做对
贴一下我没有作对的答案
private boolean isMatch(String s, int ss, String p, int pp){
if(pp >= plen){ // err1: must handle all the case where pp > plen
if(ss >= slen) return true;
else return false; // this portion is correct
}
if(pp+1 >= plen || p.charAt(pp+1) != '*'){ // the next char of pp is not *
if(ss >= slen) return false;
char pchar = p.charAt(pp), schar = s.charAt(ss);
if(pchar == '.'){
return isMatch(s,ss+1,p,pp+1);
}else{
if(pchar == schar) return isMatch(s,ss+1,p,pp+1);
else return false;
}
}else{ // the following part is bad
if(ss >= slen) return isMatch(s,ss,p,pp+2);
char pchar = p.charAt(pp), schar = s.charAt(ss);
if(pchar == '.'){
while(ss <= slen){
if(isMatch(s, ss, p, pp+2)) return true;
else ss++;
}
if(ss >= slen && pp>= plen-2) return true; //还是应该return isMatch(s,ss,p,pp+2), 本身就涵盖了这些特殊的栗子
else return false;
}else{
while(ss<slen){
schar = s.charAt(ss);
if(isMatch(s,ss,p,pp+2)) return true;
else{
if(schar == pchar) ss++;
else break;
}
}
if(ss >= slen && pp>= plen-2) return true; //err2: two cases to return
else return false;
}
}
}
比较一下非常简洁的标准答案
public class Solution {
public boolean isMatch(String word, String pat) {
return isMatch(word,0, pat, 0);
}
public boolean isMatch(String word, int w, String pat, int p){
if(p>=pat.length()) return w>=word.length();
if(p+1>=pat.length() || pat.charAt(p+1) != '*'){
if(w>=word.length()) return false;
return (pat.charAt(p) == word.charAt(w) || (pat.charAt(p)=='.' && w<word.length())) && isMatch(word,w+1,pat,p+1);
}
//next char is '*'
while((pat.charAt(p)=='.' && w<word.length()) || (w<word.length() && word.charAt(w) == pat.charAt(p))){
if(isMatch(word,w,pat,p+2)) return true;
w++;
}
return isMatch(word,w,pat,p+2);
}
}