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:
scould be empty and contains only lowercase lettersa-z.pcould 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
pis empty, check ifsis also empty. -
If
phas length 1, check ifsis 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 ofsand starting from the second character ofp. -
If
p’s second character is*. Whilesis not empty andpands’s first character match, ifsand starting from the third character ofpmatch returntrue, else remove the first character ofsand 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
swithpthat starts from the third character, in other words, compare “ab” fromsand “ab” fromp. If the first character are not matched, then we compare “b” fromsand “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
sand compare withpagain, which iss = a bandp = 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
swithpstarting 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
bfromsand the third character ofp, which isb.
- From the above example, we check the last
Solution
1 | |