题解 | #字符串通配符#

字符串通配符

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')

全部评论

相关推荐

10-28 15:45
门头沟学院 C++
西南山:海康威视之前不是大规模裁员吗
点赞 评论 收藏
分享
offer多多的六边形战士很无语:看了你的博客,感觉挺不错的,可以把你的访问量和粉丝数在简历里提一下,闪光点(仅个人意见)
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务