CodeArchon

hard2-D Dynamic ProgrammingGoogleFacebook

Pattern Shell Validator

A mini-regex engine supports '.' (any char) and '*' (zero or more of the previous char) and must match the whole input.

Given a string s and pattern p with '.' and '*', return true iff p fully matches s.

Choose approach

T
F
T
F
T
F
?
F
F
T
T
F
row
?
?
?
?
?
?
?
?
?
?
?
?
1/4
Narrationstep 1 of 4

Row 1 filled (s[0..0] = "a").

1def isMatch(s, p):
2 m, n = len(s), len(p)
3 dp = [[False]*(n+1) for _ in range(m+1)]
4 dp[0][0] = True
5 for j in range(1, n+1):
6 if p[j-1] == '*': dp[0][j] = dp[0][j-2]
7 for i in range(1, m+1):
8 for j in range(1, n+1):
9 if p[j-1] in ('.', s[i-1]): dp[i][j] = dp[i-1][j-1]
10 elif p[j-1] == '*':
11 dp[i][j] = dp[i][j-2] or ((p[j-2] in ('.', s[i-1])) and dp[i-1][j])
12 return dp[m][n]
Variables
i=1

How to think about it

  1. Row 0 handles leading x*y*z* patterns.
  2. Full match is dp[m][n].

Edge cases to catch in interview

  • Empty pattern -> only matches empty.
  • Pattern "a*" matches "" and "aaa".

Examples

Example 1true
{"s":"ab","p":".*"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed