Problem
Given an input string (s) and a pattern (p), implement wildcard pattern 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
-
We can use dynamic programming to solve this problem.
-
First, if pattern
pis empty and stringsis also empty, then we returntrue. -
Basecase, leftmost column, we know that if
pis not empty, butsis empty. Then we need to check ifphas only one character and that character ofpis*, if it is*, then it can be true. Else, it is false. -
Basecase, top row, if
pis empty, butsis not empty, return false. -
If
p’s current character matchs’s current character, then its result is the sameboolean check(p.substring(0, pCur-1), s.substring(0, sCur-1), in other word, same as top left corner result. -
Else if
p’s current character is*, then we consider two cases: case1,*serves as empty, then we returnboolean check(p.substring(0, pCur-1), s), in other word, same as top result. For example,p=abc*ands=abc. -
Case2,
*serves as not empty, then we returnboolean check(p, s.substring(0, sCur-1), in other word, same as left result. For example,p=abc*ands=abcde, the result is same asp=abc*ands=abcd, thenp=abc*ands=abc. -
At the end, we can return the bottom right corner result.
Solution
1 | |