Engineering platform~35 min2s · 256 MBtarget O(n × m) time, O(n) spaceclassic twin: lc-44dp
An API gateway routes requests by matching the path of a request against patterns. A pattern is made of letters, question marks and stars. A question mark matches exactly one letter, and a star matches any run of letters, including no letters at all.
For this check the path is reduced to lowercase letters. A pattern matches a path only when it matches the whole path, from the first letter to the last.
Write route_matches(route, pattern).
route is the path of a request, lowercase letters.pattern is made of lowercase letters, ? and *.true when the pattern matches the whole route, and false otherwise.Input: route = "orders", pattern = "o*e?s"
Output: trueLet match[j][i] say whether the first j symbols of the pattern match the first i letters of the route. With nothing used on both sides, the answer is yes. A letter or ? takes exactly one route letter: match[j][i] = match[j - 1][i - 1] and the letters agree, or the symbol is ?. A * matches nothing, which is match[j - 1][i], or one more letter than before, which is match[j][i - 1].
| pattern \ route | (none) | o | r | d | e | r | s |
|---|---|---|---|---|---|---|---|
| (none) | yes | no | no | no | no | no | no |
| o | no | yes | no | no | no | no | no |
| * | no | yes | yes | yes | yes | yes | yes |
| e | no | no | no | no | yes | no | no |
| ? | no | no | no | no | no | yes | no |
| s | no | no | no | no | no | no | yes |
The last cell is yes. The pattern o, *, e, ?, s takes o, then rd, then e, then r, then s.
Input: route = "abc", pattern = "a?"
Output: falseThe pattern covers two letters, and the route has three.
Input: route = "ab", pattern = "*"
Output: trueA star matches any run of letters, so it matches the whole route.
1 ≤ len(route) ≤ 1000 and 1 ≤ len(pattern) ≤ 1000route contains lowercase letters. pattern contains lowercase letters, ? and *.The table has up to 1,001 × 1,001 = about a million cells, and each takes one step. A pattern with many stars can match a route in an exponential number of ways, so trying every way is impossible.