Advertisement
Guest User

Untitled

a guest
Oct 13th, 2015
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. class Solution {
  2. public:
  3. bool isMatch(string s, string p) {
  4. if (p.empty()) return s.empty();
  5.  
  6. if ('*' == p[1])
  7. // x* matches empty string or at least one character: x* -> xx*
  8. // *s is to ensure s is non-empty
  9. return (isMatch(s, p.substr(2)) || !s.empty() && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p));
  10. else
  11. return !s.empty() && (s[0] == p[0] || '.' == p[0]) && isMatch(s.substr(1), p.substr(1));
  12. }
  13. };
  14.  
  15. class Solution {
  16. public:
  17. bool isMatch(string s, string p) {
  18. /**
  19. * f[i][j]: if s[0..i-1] matches p[0..j-1]
  20. * if p[j - 1] != '*'
  21. * f[i][j] = f[i - 1][j - 1] && s[i - 1] == p[j - 1]
  22. * if p[j - 1] == '*', denote p[j - 2] with x
  23. * f[i][j] is true iff any of the following is true
  24. * 1) "x*" repeats 0 time and matches empty: f[i][j - 2]
  25. * 2) "x*" repeats >= 1 times and matches "x*x": s[i - 1] == x && f[i - 1][j]
  26. * '.' matches any single character
  27. */
  28. int m = s.size(), n = p.size();
  29. vector<vector<bool>> f(m + 1, vector<bool>(n + 1, false));
  30.  
  31. f[0][0] = true;
  32. for (int i = 1; i <= m; i++)
  33. f[i][0] = false;
  34. // p[0.., j - 3, j - 2, j - 1] matches empty iff p[j - 1] is '*' and p[0..j - 3] matches empty
  35. for (int j = 1; j <= n; j++)
  36. f[0][j] = j > 1 && '*' == p[j - 1] && f[0][j - 2];
  37.  
  38. for (int i = 1; i <= m; i++)
  39. for (int j = 1; j <= n; j++)
  40. if (p[j - 1] != '*')
  41. f[i][j] = f[i - 1][j - 1] && (s[i - 1] == p[j - 1] || '.' == p[j - 1]);
  42. else
  43. // p[0] cannot be '*' so no need to check "j > 1" here
  44. f[i][j] = f[i][j - 2] || (s[i - 1] == p[j - 2] || '.' == p[j - 2]) && f[i - 1][j];
  45.  
  46. return f[m][n];
  47. }
  48. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement