标签:
This problem has a typical solution using Dynamic Programming. We define the state P[i][j] to be true if s[0..i) matches p[0..j) and false otherwise. Then the state equations are:
Putting these together, we will have the following code.
1 class Solution { 2 public: 3 bool isMatch(string s, string p) { 4 int m = s.length(), n = p.length(); 5 vector<vector<bool> > dp(m + 1, vector<bool> (n + 1, false)); 6 dp[0][0] = true; 7 for (int j = 1; j <= n; j++) 8 dp[0][j] = (j > 1 && p[j - 1] == ‘*‘ && dp[0][j - 2]); 9 for (int j = 1; j <= n; j++) { 10 for (int i = 1; i <= m; i++) { 11 if (p[j - 1] == ‘*‘) 12 dp[i][j] = dp[i][j - 2] || ((s[i - 1] == p[j - 2] || p[j - 2] == ‘.‘) && dp[i - 1][j]); 13 else dp[i][j] = dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == ‘.‘); 14 } 15 } 16 return dp[m][n]; 17 } 18 };
[LeetCode] Regular Expression Matching
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4623211.html