JZ52 正则表达式匹配
my version 错误记录
- “aaa”,“a*a” 未通过
- “” , “.*” 未通过
- “”,"." 未通过
- “a”,".*" 未通过
- “ab”,".*" 未通过
class Solution:
def match(self , string , pattern ):
p_string = 0
p_pattern = 0
while p_string < len(string):
if p_pattern >= len(pattern):
return False
else:
if str[p_string] == pattern[p_pattern] or pattern[p_pattern]=='.':
p_string += 1
p_pattern += 1
elif pattern[p_pattern] == '*':
pre_str = str[p_string]
pre_pattern = pattern[p_pattern]
if pre_pattern != '.':
if p_pattern+1 < len(pattern) and pattern[p_pattern] != pre_str:
while p_string < len(string) and string[p_string] == pre_str:
p_string += 1
else:
len_str = 0
len_pattern = 0
while p_string < len(string) and string[p_string] == pre_str:
p_string += 1
len_str += 1
if p_pattern+1 < len(pattern):
p_pattern += 1
while p_pattern < len(pattern) and pattern[p_pattern] == pre_str:
p_pattern += 1
len_pattern += 1
if len_pattern > len_str:
return False
else:
pass
if p_pattern < len(pattern) and pattern[p_pattern] == '*':
p_pattern += 1
while p_pattern+1 < len(pattern) and pattern[p_pattern+1]=='*':
p_pattern += 2
if p_string == len(string) and p_pattern == len(pattern):
return True
else:
return False
自己做不出来 不做了! QAQ 解决不了’’.*’'的问题
book method1
class Solution:
def eq(self, char_str, char_pat):
if char_str == char_pat or char_pat == '.':
return True
return False
def dp(self, string, pattern, str_idx, pat_idx):
if self.found:
return
if str_idx == len(string) and pat_idx == len(pattern):
self.found = True
return
if str_idx == len(string) or pat_idx == len(pattern):
return
if self.eq(string[str_idx], pattern[pat_idx][0]):
if pattern[pat_idx][1]:
self.dp(string, pattern, str_idx + 1, pat_idx)
self.dp(string, pattern, str_idx + 1, pat_idx + 1)
self.dp(string, pattern, str_idx, pat_idx + 1)
else:
self.dp(string, pattern, str_idx + 1, pat_idx + 1)
else:
if pattern[pat_idx][1]:
self.dp(string, pattern, str_idx, pat_idx + 1)
return
def match(self , string , pattern ):
string += '#'
pattern += '#'
self.found = False;
string = list(string)
pattern2 = []
for char in list(pattern):
if char != '*':
pattern2.append([char, False])
else:
pattern2[-1][1] = True
self.dp(string, pattern2, 0, 0)
return self.found
|