[LintCode] 正则表达式匹配
1 class Solution { 2 public: 3 /** 4 * @param s: A string 5 * @param p: A string includes "." and "*" 6 * @return: A boolean 7 */ 8 bool isMatch(const char *s, const char *p) { 9 // write your code here 10 int m = strlen(s), n = strlen(p); 11 vector<vector<bool> > dp(m + 1, vector<bool> (n + 1, false)); 12 dp[0][0] = true; 13 for (int j = 1; j <= n; j++) 14 dp[0][j] = (j > 1 && p[j - 1] == '*' && dp[0][j - 2]); 15 for (int j = 1; j <= n; j++) { 16 for (int i = 1; i <= m; i++) { 17 if (j > 1 && p[j - 1] == '*') 18 dp[i][j] = dp[i][j - 2] || ((s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]); 19 else dp[i][j] = dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.'); 20 } 21 } 22 return dp[m][n]; 23 } 24 };