正则表达式匹配
题目描述
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。
- ‘.’ 匹配任意单个字符
- ‘*’ 匹配零个或多个前面的那一个元素
- 所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
示例 1:
- 输入:
- s = “aa”
- p = “a”
- 输出: false
- 解释: “a” 无法匹配 “aa” 整个字符串。
示例 2:
- 输入:
- s = “aa”
- p = “a*”
- 输出: true
- 解释: 因为 ‘*’ 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 ‘a’。因此,字符串 “aa” 可被视为 ‘a’ 重复了一次。
示例 3:
- 输入:
- s = “ab”
- p = “.*”
输出: true
- 解释: "." 表示可匹配零个或多个(’’)任意字符(’.’)。
示例 4:
- 输入:
- s = “aab”
- p = “cab”
- 输出: true
- 解释: 因为 ‘*’ 表示零个或多个,这里 ‘c’ 为 0 个, ‘a’ 被重复一次。因此可以匹配字符串 “aab”。
示例 5:
- 输入:
- s =
- p =
- 输出: false
题解
解题思路
- 如果p和s都是空串,显然是匹配的。
- 当匹配到 的时候。s 和 p 是否匹配取决于s[1:]和p是否匹配或者s和p[2:]是否匹配。
- 当匹配到 (l:表示字母)的时候。s 和 p 是否匹配取决于s[1:]和p是否匹配或者s和p[2:]是否匹配。
- 当只是字母相等的时候。s 和 p 是否匹配取决于s[1:]和p[1:]是否匹配。
python代码
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if len(s) == 0 and len(p) == 0:
return True
if len(s) == 0 or len(p) == 0:
if len(p) == 1: return False
if len(s) == 0 and p[1] == '*':
return self.isMatch(s, p[2:])
return False
unmatched = False
if s[0] != p[0] and p[0] != '.':
if len(p) == 1:
unmatched = True
if len(p) >= 2 and p[1] != '*':
unmatched = True
elif len(p) >= 2 and p[1] == '*':
return self.isMatch(s, p[2:])
if unmatched:
return False
if p[0] == '.' and len(p) >= 2 and p[1] == '*':
return self.isMatch(s[1:], p) or self.isMatch(s, p[2:])
elif p[0] != '.' and len(p) >= 2 and p[1] == '*':
return self.isMatch(s[1:], p) or self.isMatch(s, p[2:])
else:
return self.isMatch(s[1:], p[1:])
完整python代码
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if len(s) == 0 and len(p) == 0:
return True
if len(s) == 0 or len(p) == 0:
if len(p) == 1: return False
if len(s) == 0 and p[1] == '*':
return self.isMatch(s, p[2:])
return False
unmatched = False
if s[0] != p[0] and p[0] != '.':
if len(p) == 1:
unmatched = True
if len(p) >= 2 and p[1] != '*':
unmatched = True
elif len(p) >= 2 and p[1] == '*':
return self.isMatch(s, p[2:])
if unmatched:
return False
if p[0] == '.' and len(p) >= 2 and p[1] == '*':
return self.isMatch(s[1:], p) or self.isMatch(s, p[2:])
elif p[0] != '.' and len(p) >= 2 and p[1] == '*':
return self.isMatch(s[1:], p) or self.isMatch(s, p[2:])
else:
return self.isMatch(s[1:], p[1:])
def stringToString(input):
return input[1:-1].decode('string_escape')
def main():
import sys
import io
def readlines():
for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
yield line.strip('\n')
lines = readlines()
while True:
try:
line = next(lines)
s = stringToString(line);
line = next(lines)
p = stringToString(line);
ret = Solution().isMatch(s, p)
out = (ret);
print(out)
except StopIteration:
break
if __name__ == '__main__':
main()