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:

  1. bool isMatch(const char *s, const char *p)

Some examples:

  1. isMatch("aa","a") false
  2. isMatch("aa","aa") true
  3. isMatch("aaa","aa") false
  4. isMatch("aa", "a*") true
  5. isMatch("aa", ".*") true
  6. isMatch("ab", ".*") true
  7. isMatch("aab", "c*a*b") true

分析

这是一道很有挑战的题。

递归版

  1. // Regular Expression Matching
  2. // Time complexity: O(n)
  3. // Space complexity: O(1)
  4. class Solution {
  5. public:
  6. bool isMatch(const string& s, const string& p) {
  7. return isMatch(s.c_str(), p.c_str());
  8. }
  9. private:
  10. bool matchFirst(const char *s, const char *p) {
  11. return *p == *s || (*p == '.' && *s != '\0');
  12. }
  13. bool isMatch(const char *s, const char *p) {
  14. if (*p == '\0') return *s == '\0'; //empty
  15. // next char is not '*', then must match current character
  16. if (*(p + 1) != '*') {
  17. if (matchFirst(s, p)) return isMatch(s + 1, p + 1);
  18. else return false;
  19. } else { // next char is '*'
  20. if (isMatch(s, p + 2)) return true; // try the length of 0
  21. while ( matchFirst(s, p) ) // try all possible lengths
  22. if (isMatch(++s, p + 2)) return true;
  23. return false;
  24. }
  25. }
  26. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/string/regular-expression-matching.html