|
| 1 | +/* |
| 2 | + '.' Matches any single character. |
| 3 | + '*' Matches zero or more of the preceding element. |
| 4 | +
|
| 5 | + The matching should cover the entire input string (not partial). |
| 6 | +
|
| 7 | + The function prototype should be: |
| 8 | + bool isMatch(const char *s, const char *p) |
| 9 | +
|
| 10 | + Some examples: |
| 11 | + isMatch("aa","a") ¡ú false |
| 12 | + isMatch("aa","aa") ¡ú true |
| 13 | + isMatch("aaa","aa") ¡ú false |
| 14 | + isMatch("aa", "a*") ¡ú true |
| 15 | + isMatch("aa", ".*") ¡ú true |
| 16 | + isMatch("ab", ".*") ¡ú true |
| 17 | + isMatch("aab", "c*a*b") ¡ú true |
| 18 | +*/ |
| 19 | + |
| 20 | +class Solution { |
| 21 | +public: |
| 22 | + bool isEqual(char s, char p) { |
| 23 | + if (s == p || p == '.' && s != '\0') return true; |
| 24 | + return false; |
| 25 | + } |
| 26 | + |
| 27 | + bool isMatch(const char *s, const char *p) { |
| 28 | + if (*s == '\0' && *p == '\0') return true; |
| 29 | + |
| 30 | + if (*p != '\0' && *(p + 1) == '*') { |
| 31 | + // '*' represents zero of preceding element. |
| 32 | + if (isMatch(s, p + 2)) return true; |
| 33 | + // '*' represents one or more of preceding element. |
| 34 | + while (isEqual(*s, *p)) { |
| 35 | + ++s; |
| 36 | + if (isMatch(s, p + 2)) return true; |
| 37 | + } |
| 38 | + } else if (isEqual(*s, *p)) { |
| 39 | + if (isMatch(s + 1, p + 1)) return true; |
| 40 | + } |
| 41 | + |
| 42 | + return false; |
| 43 | + } |
| 44 | +}; |
0 commit comments