Regular Expression Matching (. and *)?
Short answer: bool IsMatch(string s, string p) { return IsMatchHelper(s, p, 0, 0); } bool IsMatchHelper(string s, string p, int i, int j) { if (j == p.Length) return i == s.Length; bool firstMatch = (i < s.Length) && (p[j] == s[i] || p[j] == '.'); if (j + 1 < p.Length && p[j + 1] == '*') { // Two cases: // 1) Use zero occurrence of p[j] (skip) // 2) If firstMatch, consume one char in s and keep pattern at j return…
Explain a bit more
IsMatchHelper(s, p, i, j + 2) || (firstMatch && IsMatchHelper(s, p, i + 1, j)); } else { return firstMatch && IsMatchHelper(s, p, i + 1, j + 1); } Follow on: } Explanation: Recursively matches strings supporting '.' (any char) and '*' (zero or more of preceding).
Example code
bool IsMatch(string s, string p) {
return IsMatchHelper(s, p, 0, 0);
} bool IsMatchHelper(string s, string p, int i, int j) {
if (j == p.Length) return i == s.Length; bool firstMatch = (i < s.Length) && (p[j] == s[i] || p[j] == '.'); if (j + 1 < p.Length && p[j + 1] == '*')
{ // Two cases: // 1) Use zero occurrence of p[j] (skip) // 2) If firstMatch, consume one char in s and keep pattern at j return IsMatchHelper(s, p, i, j + 2) || (firstMatch && IsMatchHelper(s, p, i + 1, j)); } else {
return firstMatch && IsMatchHelper(s, p, i + 1, j + 1);
} Follow on: } Explanation: Recursively matches strings supporting '.' (any char) and '*' (zero or more of preceding).
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png