A pattern p describes a family of strings. Lowercase letters in it must appear exactly as written, and two characters are wildcards:
? stands for exactly one character, whatever it is.* stands for any run of characters, of any length, including none at all.Return true if the pattern matches the whole string s, and false otherwise. Matching only a part of s is not enough.
k and n match the first and last letters, and * covers itte in between.
? always covers one character, never two, so b?t only matches three-letter strings such as bat or bit.
Every * here matches nothing. Several stars in a row behave just like one.
Constraints
0 <= s.length <= 20000 <= p.length <= 2000s contains only lowercase English letters.p contains only lowercase English letters, ? and *.A * can cover any number of characters, so trying every length with plain recursion blows up. The only question that ever matters is whether the rest of s from position i matches the rest of p from position j.
Letters and ? are easy: each one eats exactly one character of s, so you compare and move on. All the difficulty is in *, because you don't know how much of s it should cover. In k*n against kitten, the star has to take itte, and nothing about the star itself tells you that. Only the rest of the pattern does.
Time O(n · m) worst caseSpace O(1)
The full walkthrough and code are part of Premium