跳到主要内容

Regular Expression Matching

描述

Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character. '*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:

bool isMatch(const char *s, const char *p)

Some examples:

isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

分析

这是一道很有挑战的题。

递归版

# Regular Expression Matching
# Time complexity: O(n)
# Space complexity: O(1)
class Solution:
def isMatch(self, s: str, p: str) -> bool:
return self._isMatch(s, 0, p, 0)

def _matchFirst(self, s: str, i: int, p: str, j: int) -> bool:
if j == len(p):
return i == len(s)
if i == len(s):
return j == len(p)
return p[j] == '.' or s[i] == p[j]

def _isMatch(self, s: str, i: int, p: str, j: int) -> bool:
if j == len(p):
return i == len(s)

# next char is not '*', then must match current character
b = p[j]
if j == len(p) - 1 or p[j + 1] != '*':
if self._matchFirst(s, i, p, j):
return self._isMatch(s, i + 1, p, j + 1)
else:
return False
else: # next char is '*'
if self._isMatch(s, i, p, j + 2):
return True # try the length of 0
while self._matchFirst(s, i, p, j): # try all possible lengths
i += 1
if self._isMatch(s, i, p, j + 2):
return True
return False

相关题目