10 Regular Expression Matching

1. Question

Given an input string (s) and a pattern (p), implement regular expression matching with support for'.'and'*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover theentireinput string (not partial).

Note:

  • scould be empty and contains only lowercase lettersa-z.

  • pcould be empty and contains only lowercase lettersa-z, and characters like .or *.

Example 1:

Input:

s = "aa"
p = "a"

Output:
 false

Explanation:
 "a" does not match the entire string "aa".

Example 2:

Example 3:

Example 4:

Example 5:

2. Implementation

(1) Recursion

思路: 这题要分清况讨论

  • 如果p是空,则查看s是否为空

  • 如果p长度大于1且p[1] == *, 因为这里的*必须匹配前面的字符0次或多次

    1. 如果匹配0次的话,就继续递归地比较s和p.substring(2)

      2.如果匹配多次,则需要s[0] == p[0] 或者 p[0] == '.', 然后递归地比较s.substring(1)和p

  • 如果上述情况都不成立的话,则在s[0] == p[0] 或者 p[0] == '.'的情况下,递归比较s.substring(1)和p.substring(1)

(2)DP

思路:

  1. P[i][j] = P[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.');

  2. P[i][j] = P[i][j - 2], if p[j - 1] == '*' and the pattern repeats for 0 times;

  3. P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*' and the pattern repeats for at least 1 times.

3. Time & Space Complexity

Recursion: 时间复杂度O(2^n), 因为,假设P全是a*a*a*这样组成,s = aaaaaaaa 而s的每一个字符都有2种可能:与当前的a*匹配,或者与下一个a*匹配(前一个匹配空), 这样假设s有n个字符,则实际上的复杂度是2^n, 空间复杂度O(L), L是s的长度

Last updated

Was this helpful?