momo's

Cracking LeetCode: 10. Regular Expression Matching

May
10

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

 

Thought:

DP:

f[m][n] means s[0,..,m-1] matches p[0,…,n-1]

  • If p[n-1] !=’*’, then f[m][n] = s[m-1]==p[n-1] or f[m-1][n-1]
  • If p[n-1] == ‘*’, denotes p[n-2] with x, then
    1. (“x*” repeats 0 times to match empty) f[m][n] = f[m][n-2]
    2. (“x*” repeats >=1 times to match “x*x”) f[m][n] = f[m-1][n] and s[n-1] == x

 

 

Reference:

https://discuss.leetcode.com/topic/6183/my-concise-recursive-and-dp-solutions-with-full-explanation-in-c

Tech/技术 , Comments Off on Cracking LeetCode: 10. Regular Expression Matching

Comments

Comments are closed.

Scroll Up