トピック:
入力文字列(所与s
)及びパターン(p
)をサポートする正規表現マッチング実装 '.'
とを '*'
。
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
マッチングは、カバーすべき 全 入力文字列(部分的ではないが)。
注意:
s
空と小文字のみが含まれてできましたa-z
。p
空であると小文字のみが含ま可能性がありa-z
、などの文字.
またはを*
。
例1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
例2:
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
例3:
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
例4:
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
例5:
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
間違った質問を開始:
モードそのA-A * BC *デ*平均{[(AA)* N(BC)] * N(デ)} * N [注:* nは繰り返しn回を表します]
そして、次のコードで:
class Solution:
def isMatch_without(self,s,p):
match = True
for i in range(len(s)):
if s[i] == p[i] or p[i]==".":
pass
else:
match = False
break
return match
def isMatch(self, s: str, p: str) -> bool:
# 边缘情况
if s == "":
if p == "":
return True
elif p[-1] == "*":
return True
else:
return False
match = True
ps = str.split(p, "*")
#如果不是以 * 结尾
if ps[-1] !="":
match = self.isMatch_without(s[-len(ps[-1]):],ps[-1])
if match:
s = s[:-len(ps[-1])]
else:
return False
ps.pop()
index_p = len(ps)
if index_p ==0 and s!="":
return False
while s!="":
if index_p>0:
index_p -=1
else:
index_p = len(ps)-1
if len(s) >= len(ps[index_p]):
match = self.isMatch_without(s[-len(ps[index_p]):],ps[index_p])
else:
match = False
if match:
while match & (s!=""):
s = s[:-len(ps[index_p])]
if len(s) >= len(ps[index_p]):
match = self.isMatch_without(s[-len(ps[index_p]):],ps[index_p])
else:
match = False
else:
index_p = len(ps) - 1
if len(s) >= len(ps[index_p]):
match = self.isMatch_without(s[-len(ps[index_p]):],ps[index_p])
else:
match = False
if not match:
return False
else:
while match & (s!=""):
s = s[:-len(ps[index_p])]
if len(s) >= len(ps[index_p]):
match = self.isMatch_without(s[-len(ps[index_p]):],ps[index_p])
else:
match = False
return True
これは、被写体がそれほど複雑ではないことがわかりました
モードは、AA * BC *デ*手段です。
()* NB(C)* ND(E)* nは、その結果、これは、問題のバックトラックとなります。X用*モードでは、2つの手順が必要です。
1、sは削除X(X時間はでS 0繰り返す)しない、X *削除パターンPが通過するか否かを判断します。
図2は、デッドエンドは、S削除され、X、X * pがモード(連続を通じてバックトラック、削除n回のX、X * Pは削除するように実装されてもよい)を介して移動するか否かを判断する保持します
class Solution:
def isMatch(self, s: str, p: str) -> bool:
i = len(p)-1
while i >=0:
if p[i] == "*":
i -= 1
# 假设s中不包含 * 前面的字符,尝试看是否走得通
if self.isMatch(s,p[:i]):
return True
# 走不通,回溯,看能否删一个字符
else:
while len(s)>0:
if p[i]=="." or s[-1]==p[i]:
s = s[:-1]
if self.isMatch(s,p[:i]):
return True
else:
i -= 1
break
# 不含*的普通模式,没有分枝
else:
if len(s)>0:
if p[i]=="." or s[-1]==p[i]:
i -= 1
s = s[:-1]
else:
return False
else:
return False
if len(s) ==0:
return True
else:
return False
この問題は、多国間の角以下の特別な配慮があるだろう、戻っていない、バックでなければなりません。