Regular Expression Matching
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
思路:对于字符串匹配,s[i]和p[j].此题的关键就在于p[j+1]是否为'*'.递归思路解题。
如果p[j+1]!='*',s[i]==p[j],则匹配下一位(i+1,j+1),如果s[i]!=p[j],匹配失败
如果p[j+1]=='*',s[i]==p[j],则匹配(i,j+2)或者(i+1,j+2),如果s[i]!=p[j],则匹配(i,j+2)
class Solution { public: bool isMatch(const char *s, const char *p) { if(*p=='\0') return *s=='\0'; if(*(p+1)!='*') { while(*s!='\0' && (*s==*p || *p=='.')) { return isMatch(s+1,p+1); } } else { while(*s!='\0' && (*s==*p||*p=='.')) { if(isMatch(s,p+2)) return true; s++; } return isMatch(s,p+2); } return false; } };
使用动态规划解题,思路和上述很相似,dp[j][i]表示s[0..j]和p[0...j]是否匹配;
class Solution { public: bool isMatch(const char *s, const char *p) { int slen=strlen(s); int plen=strlen(p); vector<vector<bool> > dp(slen+1,vector<bool>(plen+1,false)); dp[0][0]=true; for(int i=1;i<=plen;++i) { if(p[i]!='*') { for(int j=1;j<=slen;++j) { dp[j][i]=(dp[j-1][i-1] && (s[j-1]==p[i-1]||p[i-1]=='.')); } } else { dp[0][i]=dp[0][i+1]=dp[0][i-1]; for(int j=1;j<=slen;++j) { dp[j][i]=dp[j][i+1]=(dp[j-1][i]&&(s[j-1]==p[i-1] || p[i-1]=='.')||dp[j][i-1]); } ++i; } } return dp[slen][plen]; } };