10 Regular Expression Matching

1. Question

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:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

2. Implementation

(1) Recursion

思路: 我们从后往前匹配,这样的方法好处是一旦我们遇到"*",由于*的在这里的特性是匹配前一个字符0至多次,这样的话我们只要检查*前的一个字符是否和当前p的字符相同即可。在从后往前匹配的过程中,我们将过程分成几个cases:

1.如果pIndex = -1时,说明我们已经匹配完p的所有字符,这时只有当sIndex也等于-1时我们才return true

2.如果p.charAt(pIndex) = ‘*’时

(2) DP

3. Time & Space Complexity

Last updated

Was this helpful?