从字符串string开始完整匹配子串sub,返回匹配到的字符个数。
sub中如果出现'?'表示可以匹配一到三个除'\0'以外的任意字符。
如果sub还有找不到匹配的字符,则说明不能完整匹配。
如果能完整匹配,返回匹配到的字符个数,如果有多种匹配方式,返回匹配字符数最少的那个,如果不能完整匹配,返回-1
第一行输入字符串string,长度小于10000
第二行输入子串sub,长度小于100
从string开头位置完整匹配sub,匹配到的字符个数。
abcdefg a?c
3
aabcddefg a?c
4
aabcddefg b?e
-1
aabcddefg a?d
5
def check(list1, str1): for ll in list1: if ll not in str1: return -1 if str1.find(list1[0]) != 0: return -1 return 1 def func(str1, substr): locate = [] res = [] if substr in str1: print(len(substr)) if '?' in substr: count1 = substr.count('?') list1 = substr.split('?', count1) #print(list1) if check(list1, str1) == -1: return -1 for i in range(len(list1)): locate.append(str1.find(list1[i])) i += str1.find(list1[i]) #print(locate) for j in range(1, len(locate)): res.append(locate[j] - (locate[j - 1] + len(list1[j - 1]) - 1)) #print(res) for rr in res: if rr > 4: return -1 return locate[-1] + len(list1[-1]) - locate[0] else: return -1 str1 = input() substr = input() print(func(str1, substr))
import re def maxProfit(string, sub): tmp_sub = "^" + sub.replace("?", "[\s|\S]{1,3}?") ls = re.findall(tmp_sub, string) min_len = len(string) if len(ls): for i in ls: min_len = min(min_len, len(i)) return min_len return -1 _string = str(input()) _sub = str(input()) res = maxProfit(_string, _sub) print(str(res))利用python自带re模块进行匹配并获取最小长度
def help(s,re): if re[0]!="?" and re[0]!=s[0]: return -1 i = j = 0 while i < len(re) and j < len(s): if re[i]==s[j]: i+=1 j+=1 continue if re[i] !="?" and re[i]!=s[j]: return -1 if re[i]=="?": i+=1 j+=1 temp = j for k in range(0,3): if j+k<len(s) and re[i] == s[j+k]: i+=1 j+=k j+=1 break if j == temp: return -1 else: j+=1 if i == len(re): return j else: return -1 if __name__ == "__main__": s = input() re = input() print(help(s,re))