010 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
详见:https://leetcode.com/problems/regular-expression-matching/description/
方法一:
class Solution { public: bool isMatch(string s, string p) { if(p.empty()) { return s.empty(); } if(p.size()==1) { return (s.size()==1&&(s[0]==p[0]||p[0]=='.')); } if(p[1]!='*') { if(s.empty()) { return false; } return (s[0]==p[0]||p[0]=='.')&&isMatch(s.substr(1),p.substr(1)); } while(!s.empty()&&(s[0]==p[0]||p[0]=='.')) { if(isMatch(s,p.substr(2))) { return true; } s=s.substr(1); } return isMatch(s,p.substr(2)); } };
方法二:动态规划,dp[i][j] 表示 s[0..i] 和 p[0..j] 是否 match
class Solution { public: bool isMatch(string s, string p) { int m = s.size(), n = p.size(); vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false)); dp[0][0] = true; for (int i = 1; i <= m; i++) { dp[i][0] = false; } for (int j = 1; j <= n; j++) { dp[0][j] = j > 1 && '*' == p[j - 1] && dp[0][j - 2]; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (p[j - 1] != '*') { dp[i][j] = dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || '.' == p[j - 1]); } else { dp[i][j] = dp[i][j - 2] || (s[i - 1] == p[j - 2] || '.' == p[j - 2]) && dp[i - 1][j]; } } } return dp[m][n]; } };
参考:http://www.cnblogs.com/grandyang/p/4461713.html