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 <!--more-->
Dynamic Programming
f(i,j) represents whether the first i letters of string s can be matched by the first j letters of regular expression p(0 means no and 1 means yes).
Therefore, the recursion formula can be written as:
(1) if p[i] == '.'
, f(i,j) = f(i-1,j-1)
(2) if p[i] == '*'
,
f(i,j) = f(i,j-2) or { s[i] match p[j-1]
and f(i-1,j) }
(3) if p[i] != '.'
and p[i] != '*'
,
f(i,j) = f(i-1,j-1), when s[i] == p[j]
f(i,j) = 0, when s[i] != p[j]
- Time Complexity: O(n^2)
- Space Complexity: O(n^2)
Finding law
By observing the samples above, we can find the law and solve it directly
- Time Complexity: O(n)
- Space Complexity: O(1)