题解 | #字符串通配符#
字符串通配符
https://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036
# 一开始会错题意了,以为是按一般的正则匹配的功能去做实现,在递归的过程中走了很多弯路,分别去考虑了p*、?*这两种形式,但是写到后面发现有的用例用这种办法根本通不过,回去看题才发现需要把每一个symbol都单独考虑,难度骤减,优化调试了一下,这题给我做太久了
import sys
ipt = []
for line in sys.stdin:
ipt.append(line.strip())
rgp, string = ipt[0], ipt[1]
while '**' in rgp:
rgp = rgp.replace('**', '*') # optimizing the input formula, ** is equal to *
rpg = []
rpg = [i.lower() if i.isalpha() else i for i in rgp]
def check_string(string):
for i in string:
if not i.isdigit() and not i.isalpha() and i not in '?*.':
return False
return True
# print(check_string('h'))
def check_mapping(rpg, string):
if ''.join(rpg).count('*') == len(rpg) and len(rpg) > 0:
return True
elif rpg and not string:
return False
elif not rpg and string:
return False
elif not rpg and not string:
return True
rpg_list, string_list = rpg, list(string)
if rpg_list[0] == '?':
return check_mapping(rpg_list[1:], string[1:])
elif rpg_list[0] == '*':
return check_mapping(rpg_list[1:], string) or check_mapping(rpg_list, string[1:]) # * can replace or not replace a char, everystep I choose these two way, so a * factor can replace no char or multiple chars
else:
char = rpg_list[0]
if char != string[0]:
return False
else:
return check_mapping(rpg_list[1:], string[1:])
res, check_res = check_mapping(rpg, string), check_string(string)
if res and check_res:
print('true')
else:
print('false')