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:
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
-
We can use dynamic programming to solve this problem.
-
First, if pattern
p
is empty and strings
is also empty, then we returntrue
. -
Basecase, leftmost column, we know that if
p
is not empty, buts
is empty. Then we need to check ifp
has only one character and that character ofp
is*
, if it is*
, then it can be true. Else, it is false. -
Basecase, top row, if
p
is empty, buts
is 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 |
|