Problem
Given an input string (s
) and a pattern (p
), implement regular expression matching with support for '.'
and '*'
.
1 |
|
The matching should cover the entire input string (not partial).
Note:
s
could be empty and contains only lowercase lettersa-z
.p
could be empty and contains only lowercase lettersa-z
, and characters like.
or*
.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Example 4:
1 |
|
Example 5:
1 |
|
Explanation
-
If
p
is empty, check ifs
is also empty. -
If
p
has length 1, check ifs
is also has length 1 and their first character is match. -
If
p
’s second character is not*
, check if their first character is match and recursivly check the strings starting from the second character ofs
and starting from the second character ofp
. -
If
p
’s second character is*
. Whiles
is not empty andp
ands
’s first character match, ifs
and starting from the third character ofp
match returntrue
, else remove the first character ofs
and do the while loop again.1
2s = "ab" p = "a*ab"
or
1
2s = "b" p = "a*b"
- From the above example, the case is ` * ` repeat its previous character 0 times or the first character are not match. If the first character are matched, then we check
s
withp
that starts from the third character, in other words, compare “ab” froms
and “ab” fromp
. If the first character are not matched, then we compare “b” froms
and “b” fromp
.
1
2s = "aab" p = "a*b"
- From the above example, the case is ` * ` repeats its previous character at least one time. After we compare their first character matches, we remove the first character of
s
and compare withp
again, which iss = a b
andp = a * b
.
- From the above example, the case is ` * ` repeat its previous character 0 times or the first character are not match. If the first character are matched, then we check
-
After the while loop, check
s
withp
starting from the third character.1
2s = "aaab" p = "a*b"
or
1
2s = "xb" p = "a*b"
- From the above example, we check the last
b
froms
and the third character ofp
, which isb
.
- From the above example, we check the last
Solution
1 |
|