Substring Matching Pattern

EasyStringString Matching

Solution

Solution1: Find Index

export function hasMatch(s: string, p: string): boolean {
  const [left, right] = p.split('*');
  const leftIndex = s.indexOf(left);
  const rightIndex = s.lastIndexOf(right);
  if (leftIndex === -1 || rightIndex === -1) {
    return false;
  }
  return leftIndex + left.length <= rightIndex;
}

Complexity

  • m: s.length, n: p.length
  • Time: O(mn)O(m \cdot n)
  • Space: O(n)O(n)

Solution2: RegExp

export function hasMatch(s: string, p: string): boolean {
  return new RegExp(p.replace('*', '.*')).test(s);
}

Complexity

  • Time: O(2n)O(2^n)
  • Space: O(n)O(n)