正則表達式匹配
題目描述
給你一個字符串 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()