Search~35 min2s · 256 MBtarget O(n * m) time, O(m) spaceclassic twin: lc-10dp
A search app lets a team filter indexed file names with a small rule language. A letter in a rule matches that letter. A dot matches any one letter. A star after a letter or a dot lets that element repeat any number of times, including none.
A rule fits a file name only if it covers the whole name, from the first letter to the last. Your team lead asks you to write the test that says whether a name fits a rule.
Write name_fits_rule(name, rule).
name is a file name of lowercase letters. It can be empty.rule is made of lowercase letters, dots and stars. A star always comes right after a letter or a dot, and never first or after another star.true when the rule matches the whole name, and false otherwise.Input: name = "aab", rule = "a*b"
Output: trueBuild a table. The entry in row i and column j says whether the first i letters of the name fit the first j symbols of the rule. A T means yes, and a dot . means no.
| Letters of the name | "" | a |
a* |
a*b |
|---|---|---|---|---|
| "" | T | . | T | . |
a |
. | T | T | . |
aa |
. | . | T | . |
aab |
. | . | . | T |
The last entry is T, so the whole name fits. The star in column 2 lets row aa keep fitting: it takes one more a from the entry above.
Input: name = "ab", rule = ".*c"
Output: falseThe part .* can take any letters, but the rule ends with a plain c, and the name ends with b.
Input: name = "", rule = "a*b*"
Output: trueAn empty name fits a rule whose elements all have a star, because each star can take zero copies.
0 ≤ length of name ≤ 600, with the letters a to z1 ≤ length of rule ≤ 600, with the letters a to z, dots and starsA table of 600 × 600 has 360,000 entries, and each one needs a fixed number of steps. That is fast.
Trying the rule by recursion, without keeping results, is not. Each star can take zero, one or more letters, and the number of ways to share 600 letters among 300 starred elements has more than 100 digits.