You get a text s and a pattern p. Most pattern characters are letters that must match themselves. Two are special: . stands for any one letter, and * means the character right before it may appear any number of times, including zero.
Return true if the pattern matches all of s, from the first letter to the last. A match of only part of the text does not count.
Example 1
Input: s = "abb", p = "ab*" Output: true Why: b* takes both b's
2 more examples and the constraints
Example 2
Input: s = "ba", p = "b" Output: false Why: the pattern ends before the a is covered
Example 3
Input: s = "ab", p = "c*a." Output: true Why: c* is used zero times, a matches a, . matches b
Constraints
- 1 ≤ length of s ≤ 20 and 1 ≤ length of p ≤ 20
- s has only lower-case letters; p has lower-case letters,
.and* - Every
*comes right after a letter or a.
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Plain recursionO(2^(m+n))
- Bottom-up DP tableO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20-character inputs with many stars | Verdict |
|---|---|---|---|
| Plain recursion | O(2^(m+n)) | Fine on easy inputs, blows up on many stars | |
| Bottom-up DP table | O(m·n) | Best; 441 cells at most |
m = length of s, n = length of p.
Edge cases to test
- Star used zero times. "ab" matches "c*a.": the c* simply disappears.
- Pattern runs out early. "ba" against "b" is false; the whole text must be covered.
- Dot star.
.*can match any run of letters, but "ab" against ".*c" is still false. - Trailing stars. "a" matches "ab*" because b* can match nothing at the end.
Common mistakes
- Treating
*as a wildcard on its own instead of a repeat of the character before it. - Forgetting the zero-times case, so patterns like "c*a." never match.
- Skipping row i = 0, so an empty prefix of s never matches a pattern made of stars.
How to talk through it
- 1Clarify. Must the match cover the whole text? Can a star appear first? What does
.*mean? - 2Define the question. Does s from i on match p from j on? Every case reduces to a smaller (i, j).
- 3Give the recursion. Two choices at a star, one move otherwise; say it repeats (i, j) pairs and goes exponential.
- 4Turn it into a table. There are only (m + 1)(n + 1) pairs, so fill a DP table in O(m·n).
- 5Test out loud. Run a star used zero times, a pattern that ends early, and
.*before a letter.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?