首页 > 试题广场 >

字符串通配符

[编程题]字符串通配符
  • 热度指数:170999 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

问题描述:在计算机中,通配符一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。现要求各位实现字符串通配符的算法。
要求:
实现如下2个通配符:
*:匹配0个或以上的字符(注:能被*和?匹配的字符仅由英文字母和数字0到9组成,下同)
?:匹配1个字符

注意:匹配时不区分大小写。

输入:
通配符表达式;
一组字符串。

输出:

返回不区分大小写的匹配结果,匹配成功输出true,匹配失败输出false
数据范围:字符串长度:
进阶:时间复杂度:,空间复杂度:

输入描述:

先输入一个带有通配符的字符串,再输入一个需要匹配的字符串



输出描述:

返回不区分大小写的匹配结果,匹配成功输出true,匹配失败输出false

示例1

输入

te?t*.*
txt12.xls

输出

false
示例2

输入

z
zz

输出

false
示例3

输入

pq
pppq

输出

false
示例4

输入

**Z
0QZz

输出

true
示例5

输入

?*Bc*?
abcd

输出

true
示例6

输入

h*?*a
h#a

输出

false

说明

根据题目描述可知能被*和?匹配的字符仅由英文字母和数字0到9组成,所以?不能匹配#,故输出false      
示例7

输入

p*p*qp**pq*p**p***ppq
pppppppqppqqppqppppqqqppqppqpqqqppqpqpppqpppqpqqqpqqp

输出

false
稀里糊涂做出来了,想问下为啥倒着匹配可以,正着匹配不行?
def foo(s1: str, s2: str) -> bool:
    l1, l2 = len(s1), len(s2)
    if l1 == 0 and l2 == 0:
        return True
    elif l1 == 0:
        return False
    elif l2 == 0:
        if s1 == "*" * l1:
            return True
        else:
            return False
    else:
        p1, p2 = 0, 0
        while p1 < l1 and p2 < l2:
            if s1[p1] == "*":
                if s2[p2].isalnum():
                    return (
                        foo(s1[p1:], s2[p2 + 1 :])
                       &nbs***bsp;foo(s1[p1 + 1 :], s2[p2 + 1 :])
                       &nbs***bsp;foo(s1[p1 + 1 :], s2[p2:])
                    )
                else:
                    p1 += 1
                    continue
            elif s1[p1] == "?":
                if s2[p2].isalnum():
                    p1 += 1
                    p2 += 1
                    continue
                else:
                    return False
            else:
                if s1[p1] == s2[p2]:
                    p1 += 1
                    p2 += 1
                    continue
                else:
                    return False

        if p1 == l1 and p2 < l2:
            return False
        elif p1 < l1 and p2 == l2:
            if len(s1[p1:].replace("*", "")) == 0:
                return True
            else:
                return False
        else:
            return True


a, b = input().lower()[::-1], input().lower()[::-1]
x = "true" if foo(a, b) else "false"
print(x)


发表于 2024-09-25 21:41:11 回复(0)
aa = "0"+input()
bb = "0"+input()
a = []
b = []
for i in range(len(aa)):
    if aa[i].isupper():
        a.append(aa[i].lower())
    else:
        a.append(aa[i])
for j in range(len(bb)):
    if bb[j].isupper():
        b.append(bb[i].lower())
    else:
        b.append(bb[j])

def pd(s):
    if s.islower():
        return True
    elif s.isupper():
        return True
    elif s in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
        return True
    else:
        return False


def qu_xing(lst):
    # 使用列表推导式创建一个新列表,其中不包含'*'元素
    return [item for item in lst if item != "*"]


dp = [["0" for k in range(len(b)+1)] for i in range(len(a)+1)]
dp[0][0] = "1"

# 判断边缘
for i in range(1,len(a)):
    if qu_xing(a[0:i+1]) == ["0"]:
        dp[i][0] = "1"


for i in range(1, len(a)):
    for j in range(1, len(b)):  # 判断a的0~i和b的0~j是否匹配
        if pd(b[j]):
            if a[i] == "*":
                if dp[i-1][j] == "1":
                    dp[i][j] = "1"
                else:
                    dp[i][j] = dp[i][j - 1]
            elif a[i] == "?":
                dp[i][j] = dp[i - 1][j - 1]
            elif a[i] == b[j]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = "0"
        elif a[i] == b[j]:
            dp[i][j] = dp[i - 1][j - 1]
        elif a[i] == "*":
            if dp[i - 1][j] == "1":
                dp[i][j] = "1"
            else:
                dp[i][j] = "0"
        else:
            dp[i][j] = "0"

if dp[len(a) - 1][len(b) - 1] == "1":
    print("true")
else:
    print("false")

发表于 2024-06-19 03:21:27 回复(0)
投机取巧法,重点在于先转换大小写,并且将所有连续的*合并,这样计算较快。
import sys
import re
modStr = input().upper()
mainStr = input().upper()
while modStr.count("**")>0:
    modStr = modStr.replace("**","*")
modStr = modStr.replace("?",r"[A-Z0-9]{1}")
modStr = modStr.replace("*",r"[A-Z0-9]{0,}")
modStr = modStr.replace(".",r"\.")
#print(modStr)
res = re.fullmatch(modStr,mainStr)
if res==None:
    print("false")
else:
    print("true")

mainStr = input().upper()
while modStr.count("**")>0:
    modStr = modStr.replace("**","*")
modStr = modStr.replace("?",r"[A-Z0-9]{1}")
modStr = modStr.replace("*",r"[A-Z0-9]{0,}")
modStr = modStr.replace(".",r"\.")
#print(modStr)
res = re.fullmatch(modStr,mainStr)
if res==None:
    print("false")
else:
    print("true")

发表于 2024-02-14 21:27:27 回复(1)
import sys

a = list(input().lower())
b = list(input().lower())

dp = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)]
dp[0][0] = True
for i in range(1,len(a)+1):
    dp[i][0] = dp[i-1][0] and a[i-1]=='*'
for i in range(1,len(a)+1):
    for j in range(1,len(b)+1):
        dp[0][j] = False
        if a[i-1]!='*':
            if a[i-1]==b[j-1]&nbs***bsp;(a[i-1]=='?' and b[j-1].isalnum()):
                dp[i][j]=dp[i-1][j-1]
        elif a[i-1]=='*':
            dp[i][j]=dp[i-1][j]&nbs***bsp;(b[j-1].isalnum() and dp[i][j-1])
if dp[len(a)][len(b)]:
    print('true')
else:
    print('false')
动态规划~
发表于 2023-04-20 22:26:07 回复(0)
#发现大家和测试用例都有点没考虑到哈,当输入为h*?*和h#a#时,
#返回仍然为true,不合理的,但我也没想到解决办法哈哈哈
def fun(str1, str2):
    if str1 == '' and str2 == '':
        return True
    elif str1 == '' and str2 != '':
        return False
    elif str1 != '' and str2 == '':
        if str1.replace('*', '') == '':
            return True
        else:
            return False
    else:
        m, n = len(str1), len(str2)
        if str1[m-1] == str2[n-1]&nbs***bsp;(str1[m-1] == '?' and str2[n-1].isalnum()):
            return fun(str1[:m-1], str2[:n-1])
        elif str1[m-1] == '*':
            return fun(str1[:m-1], str2)&nbs***bsp;fun(str1, str2[:n-1])
        else:
            return False

while True:
    try:
        str1, str2 = input().lower(), input().lower()
        if fun(str1, str2):
            print('true')
        else:
            print('false')
        
    except:
        break

发表于 2023-03-01 17:37:58 回复(0)
import re
regx, s = input().lower(), input().lower()
regx = regx.replace('.', '\.').replace('*','\w*').replace('?', '\w{1}')
c = re.findall(regx, s)
print('true' if s in c else 'false')

发表于 2022-11-23 21:19:56 回复(0)
#思路:直接用正则的fullmatch匹配
#不行
    #一是由于这里要求*?能直接匹配字符,而正则中是匹配前一项字符
    #二是?在正则中匹配一次或0次,这里只能匹配一次
    #三是用fullmatch匹配的话,会超时。可以用match匹配,看结果是否一致
#解决方法:将?替换为\w{1},将*替换为\w{0,},用match匹配,进行比较


import re
model=input().replace('?','\w{1}').replace('*', '\w{0,}')
text=input()

flag=re.match(model,text,re.I)

if flag==None&nbs***bsp;flag.group()!=text:
    print('false')
else:
    print('true')

发表于 2022-05-06 00:03:29 回复(2)
import re
while True:
    try:
        a = input()
        b = input()
        a = a.lower()
        b = b.lower()
        a = a.replace('?','[0-9a-z]{1}').replace('*','[0-9a-z]*').replace('.','\.')  #通配符变成正则表达
        c = re.findall(a,b)
        if(b in c):
            print('true')
        else:
            print('false')
    except:
        break

发表于 2022-04-06 14:46:43 回复(2)
import re
while True:
    try:
        r = input().replace('?', '\w{1}').replace('*', '\w{0,}')
        s = input()
        res = re.findall(r'{}'.format(r), s, re.IGNORECASE)
        # # 确保匹配的值和目标值相同
        print('true') if res != [] and (res[0] == s) else print('false')
    except:
        break
发表于 2022-03-06 11:45:42 回复(0)
import re
while True:
    try:
        string1 = input().lower()
        string2 = input().lower()
        string1 = string1.replace('?', '[a-z0-9]').replace('.', '\.').replace('*', '[0-9a-z]*')
        stringRegex = re.compile(string1)
        if stringRegex.search(string2) and string2 == stringRegex.search(string2).group():
            print('true')
        else:
            print('false')
    except:
        break

发表于 2022-02-01 22:23:06 回复(1)

def func(s1,s2):
    for j1 in s2:
        if (ord(j1)>=97 and ord(j1)<=122) or ord(j1)==63 or ord(j1)==42 or ord(j1)==46 or (ord(j1)>=48 and ord(j1)<=57):
            pass
        else:
            return 'false'
    if ('?' not in s1) and ('*' not in s1):
        if s1 != s2:
            return 'false'
        else:
            return 'true'
    else:
        s=''
        flag=0
        for j in range(len(s1)):
            i=s1[j]
            if flag==0:
                if i!='?' and i!='*':
                    s+=i
                else:
                    flag=1
                    s=''
                if s not in s2:
                    return 'false'
                else:
                    pass
            else:
                if i!='?' and i!='*':
                    s+=i
                else:
                    flag=0
                    s=''
                if s not in s2:
                    return 'false'
                else:
                    pass
            #x=s1.index(i)
            y=len(s1)-1
            if j==y and s!='':
                if s!=s2[-len(s):]:
                    return 'false'
    return 'true'


while True:
    try:
        s1=input().strip().lower()
        s2=input().strip().lower()
        print(func(s1,s2))
    except:
        break
发表于 2021-07-14 13:53:20 回复(1)