Problem:


Score : 300 points

Problem Statement

E869120 found a chest which is likely to contain treasure.

However, the chest is locked. In order to open it, he needs to enter a string S consisting of lowercase English letters.

He also found a string S', which turns out to be the string S with some of its letters (possibly all or none) replaced with ?.  

One more thing he found is a sheet of paper with the following facts written on it:  

Condition 1: The string S contains a string T as a contiguous substring.

Condition 2: S is the lexicographically smallest string among the ones that satisfy Condition 1.

Print the string S.

If such a string does not exist, print UNRESTORABLE.  

Constraints

1 \leq |S'|, |T| \leq 50

S' consists of lowercase English letters and ?.

T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T'

Output

Print the string S.

If such a string does not exist, print UNRESTORABLE instead.  

Sample Input 1

?tc????
coder

Sample Output 1

atcoder

There are 26 strings that satisfy Condition 1: atcoder, btcoder, ctcoder,..., ztcoder.
Among them, the lexicographically smallest is atcoder, so we can say S = atcoder.

Sample Input 2

??p??d??
abc

Sample Output 2

UNRESTORABLE

There is no string that satisfies Condition 1, so the string S does not exist.



Sample input:
?tc????
coder


Sample output:
atcoder

Submission status: Accepted

Solution code:
#!/usr/bin/env python3



# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    S = input()
    T = input()
    n = len(S)
    l = len(T)
    K = []
    for i in range(n-l+1):
        s = S[i:i+l]
        candidate = True
        for c1, c2 in zip(s, T):
            if c1 != '?' and c1 != c2:
                candidate = False
        if candidate:
            K.append(i)
    if len(K) == 0:
        print('UNRESTORABLE')
        return
    top = K[-1]
    f = S[:top].replace('?', 'a')
    t = S[top+l:].replace('?', 'a')
    print(f + T + t)
    pass

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
S = input()
T = input()

res = []
for i in range(len(S) - len(T) + 1):
    flag = True
    for j in range(len(T)):
        if S[i + j] != T[j] and S[i + j] != "?":
            flag = False
    if flag:
        U = S.replace("?", "a")
        U = U[:i] + T + U[i + len(T) :]
        res.append(U)

if res:
    print(res[-1])
else:
    print("UNRESTORABLE")

Submission status: Accepted

Solution code:
s = list(input())
t = list(input())
ans = "UNRESTORABLE"
if len(s) >= len(t):
    for i in range(len(s) - len(t) + 1):
        ss = s[i:i + len(t)]
        count = 0
        for j in range(len(ss)):
            if (ss[j] == "?") | (ss[j] == t[j]):
                count += 1
            else:
                break
        if count == len(ss):
            ans = "".join(s[:i] + t + s[i + len(t):])
    print(ans.replace("?", "a"))
else:
    print(ans)

Submission status: Accepted

Solution code:
S = list(input())
T = list(input())
ans = []

for i in range(len(S)-len(T)+1):
    for j in range(len(T)):
        if S[i+j] == '?' or S[i+j] == T[j]:
            continue
        else:
            break
    else:
        tmp = str("".join(S[:i] + T + S[i+len(T):]).replace('?','a'))
        ans.append(tmp)
if len(ans) == 0:
    print("UNRESTORABLE")
else:
    ans.sort()
    print(ans[0])

Submission status: Accepted

Solution code:
S=input()
T=input()

match = -1
for s in range(len(S)-len(T)+1):
    ok = True
    for t in range(len(T)):
        if S[s+t] == '?':
            continue
        if S[s+t] == T[t]:
            continue
        ok = False
        break
    if ok:
        #print("===")
        #print(S)
        #print(" "*s+T)
        match = s
#print(match)
if match == -1:
    print("UNRESTORABLE")
else:
    S = list(S)
    A = []
    for i in range(len(S)):
        if match <= i < match+len(T):
            A.append(T[i-match])
        else:
            if S[i] == '?':
                A.append('a')
            else:
                A.append(S[i])
    print("".join(A))

Submission status: Accepted

Solution code:
def main():
    S = input()
    T = input()
    t = len(T)
    for i in range(len(S) - t, -1, -1):
        for j in range(t):
            if S[i + j] != T[j] and S[i + j] != '?':
                break
        else:
            print((S[:i] + T + S[i + t:]).replace("?","a"))
            exit()

    print("UNRESTORABLE")
main()

Submission status: Accepted

Solution code:
S = list(input())
T = list(input())

ans_list=[]
for i in range(len(S)-len(T)+1):
    S_temp=S.copy()
    serch_S=S_temp[i:i+len(T)]
    count=0
    for t in range(len(T)):
        if serch_S[t] in [T[t],'?']:
            count+=1
        else:
            break
        
        if count==len(T):
            S_temp[i:i+len(T)]=T

            for s in range(len(S_temp)):
                if S_temp[s]=='?':
                    S_temp[s]='a'
                    
            S_temp_str=''
            for s_t in S_temp:
                S_temp_str+=s_t

            ans_list.append(S_temp_str)

if len(ans_list)>0:
    
    ans_list.sort()
    ans=ans_list[0]
else:
    ans='UNRESTORABLE'
    
print(ans)

Submission status: Accepted

Solution code:
S = input()
T = input()
len_t = len(T)
len_s = len(S)
ans = [''] * (len_s)
for i in range(len_s)[::-1]:
  if len_t-1 > i:
    break
  hasT = True
  for j in range(len_t):
    if T[j] != S[i-len_t+1+j] and S[i-len_t+1+j] != '?':
      hasT = False
      break
  if hasT:
    for j in range(len_t):
      if S[i-len_t+1+j] == '?':
        ans[i-len_t+1+j] = T[j]
    for k in range(len_s):
      if S[k] == '?' and ans[k] == '':
        ans[k] = 'a'
      elif ans[k] == '':
        ans[k] = S[k]
    print(''.join(ans))
    exit()
print('UNRESTORABLE')

Submission status: Accepted

Solution code:
S=input()
T=input()
t=len(T)
for i in range(len(S)-t+1):
    a=c=0
    for j in range(t):
        k=S[-t-i+j]
        if k ==T[j] or k=="?" :c+=1
    if c==t:
        bef=S[:len(S)-t-i].replace("?","a")
        aft=""
        if i!=0:aft=S[-i:].replace("?","a")
        print(bef+T+aft)
        exit()
print("UNRESTORABLE")

Submission status: Accepted

Solution code:
S=input()
T=input()
t=len(T)
for i in range(len(S)-t,-1,-1):
    for j in range(t):
        k=S[i+j]
        if k !=T[j] and k!="?" :break
    else:
        print((S[:i]+T+""+S[i+t:]+"").replace("?","a"))
        exit()
print("UNRESTORABLE")

Submission status: Accepted

Solution code:
S=input()
T=input()
t=len(T)
for i in range(len(S)-t,-1,-1):
    for j in range(t):
        k=S[i+j]
        if k !=T[j] and k!="?" :break
    else:
        print((S[:i]+T+S[i+t:]+"").replace("?","a"))
        exit()
print("UNRESTORABLE")

Submission status: Accepted

Solution code:
S=input()
T=input()
t=len(T)
for i in range(len(S)-t,-1,-1):
    for j in range(t):
        k=S[i+j]
        if k !=T[j] and k!="?" :break
    else:
        print((S[:i]+T+S[i+t:]).replace("?","a"))
        exit()
print("UNRESTORABLE")

Submission status: Accepted

Solution code:
s=input()
t=input()

def mch(x,y):
    l=[False]*len(x)
    for i in range(len(x)):
        if x[i]=='?':l[i]=True
        elif x[i]==y[i]:l[i]=True
    return True if all(l) else False

l=[]
for i in range(len(s)-len(t)+1):
    if mch(s[i:i+len(t)],t):l.append((s[:i]+t+s[i+len(t):]).replace('?','a'))
print('UNRESTORABLE' if len(l)==0 else sorted(l)[0])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import copy
import collections
from bisect import bisect_left
from bisect import bisect_right
from collections import defaultdict
from heapq import heappop, heappush
import math

# NO, PAY-PAY
#import numpy as np
#import statistics
#from statistics import mean, median,variance,stdev

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
 
def main():
    S = list(input())
    T = list(input())
    
    ind = []
    isOk = False
    
    for i, val in enumerate(S):
        if val == "?" or val == T[0]:
            flg = True
            if len(S)-i < len(T):
                #print(val)
                #print("{} {}".format(len(S)-i, len(T)))
                break
            for j, vol in enumerate(T):
                if S[i+j] != T[j] and S[i+j] != "?":
                    flg = False
                    break
            if flg == True:
                ind.append(i)
                isOk = True
                
    if isOk == False:
        print("UNRESTORABLE")
    else:
        ind.sort()
        tmp = ind[-1]
        for i, val in enumerate(S):
            if i == tmp:
                for j, vol in enumerate(T):
                    S[i+j] = T[j]
            else:
                if val == "?":
                    S[i] = "a"
        print("".join(S))
    
            	
if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
def main():
    S = str(input())
    T = str(input())

    if len(S) < len(T):
        print("UNRESTORABLE")
        return 0

    answers = []

    for i in range(0, len(S)-len(T)+1):
        is_ok = True
        for j in range(len(T)):
            # print(S[i+j])
            # print(T[j])
            # print("-----------------")
            if S[i+j] != "?" and S[i+j] != T[j]:
                is_ok = False
        if is_ok:
            answers.append((S[0:i:] + T + S[i+len(T)::]).replace("?","a"))

    if len(answers) == 0:
        print("UNRESTORABLE")
        return 0
    else:
        answer = sorted(answers)[0]
        print(answer)
        return 0


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = input()
t = input()
flag = False
for i in range(len(s) - len(t) + 1):
    part = s[len(s) - len(t) - i: len(s) - i]
    flag2 = True
    for j in range(len(t)):
        if part[j] == t[j] or part[j] == "?":
            pass
        else:
            flag2 = False
            break
    if flag2 == True:
        flag = True
        ans = s[:len(s) - len(t) - i] + t + s[len(s) - i:]
        break
if flag == False:
    print("UNRESTORABLE")
else:
    print(ans.replace("?", "a"))

Submission status: Accepted

Solution code:
import re
S = input().replace('?', '.')
T = input()
for i in range(len(S)-len(T), -1, -1):
    if re.match(S[i:i+len(T)], T):
        S = S.replace('.', 'a')
        print(S[:i]+T+S[i+len(T):])
        exit()
print('UNRESTORABLE')

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def main():
    s = input()
    t = input()
    T = len(t)

    candidate = []

    for i in range(len(s)-T+1):
        buf = s[i:i+T]
        flag = True
        for b, tc in zip(buf, t):
            if b == "?" or b == tc:
                continue
            else:
                flag = False
                break
        if flag == True:
            candidate.append(i)

    if len(candidate) == 0:
        print("UNRESTORABLE")
    else:
        print((s[:candidate[-1]] + t + s[candidate[-1]+T:]).replace("?", "a"))

    pass


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc076/tasks/abc076_c
# C - Dubious Document 2

blank_s = input().split()[0]
t = input().split()[0]

matched_index_list = []

for i in range(len(blank_s) - len(t) + 1):
    is_match = True
    for s_char, t_char in zip(blank_s[i:i+len(t)], t):
        if s_char != '?' and s_char != t_char:
            is_match = False
            break

    if is_match:
        matched_index_list.append(i)

if not matched_index_list:
    answer = 'UNRESTORABLE'
else:
    replaced_s_list = []
    for index in matched_index_list:
        replaced_s = list(blank_s)
        replaced_s[index:index+len(t)] = t
        replaced_s = ''.join(replaced_s)
        replaced_s = replaced_s.replace('?', 'a')
        replaced_s_list.append(replaced_s)

    answer = min(replaced_s_list)

print(answer)

Submission status: Accepted

Solution code:
S = list(input())
T = list(input())


ans = 0
for j in range(len(S)-len(T)+1):
    can = True
    SS = S[:]
    for i, t in enumerate(T):
        s = S[j+i]
        if s != '?' and s != t:
            can = False
            break
        elif s == '?':
            SS[j+i] = t
    if can:
        ans = SS

if ans == 0:
    print('UNRESTORABLE')
else:
    Ans = ans[:]
    for i, a in enumerate(ans):
        if a == '?':
            Ans[i] = 'a'
    print(''.join(Ans))

Submission status: Accepted

Solution code:
import re
S = input().replace('?', '.')
T = input()
for i in range(len(S)-len(T), -1, -1):
    if re.match(S[i:i+len(T)], T):
        S = S.replace('.', 'a')
        print(S[:i]+T+S[i+len(T):])
        exit()
print('UNRESTORABLE')

Submission status: Accepted

Solution code:
S = input()
T = input()

for i in range(len(S) - len(T), -1, -1) :
    for j, t in enumerate(T) :
        if S[i + j] == '?' :
            continue
        if S[i + j] != t :
            break
    else :
        ans = list(S)
        ans[i: i + len(T)] = T
        print(''.join(ans).replace('?', 'a'))
        break
else :
    print('UNRESTORABLE')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
#ABC073C

def checkstr(sd,t,i):
	#sdのi文字目以降がtと等しいかチェック

	for j in range(0,len(t)):
		if(sd[j+i]!=t[j])and(sd[j+i]!='?'):
			return -1
	return i

sd = input()
t = input()

j=-1
for i in range(0,len(sd)-len(t)+1):
#	print(len(sd))
#	print(len(t))
#	print(len(sd)-len(t)-i)
	ret = checkstr(sd,t,len(sd)-len(t)-i)
	if(ret>=0):
		j=len(sd)-len(t)-i
		break

str_list = list(sd)
for i in range(0,len(sd)):
	if(str_list[i]=='?'):
		str_list[i]='a'
if(j!=-1):
	for i in range(0,len(t)):
		str_list[j+i]=t[i]

	sd_res = "".join(str_list)
	print(sd_res)
else:
	print("UNRESTORABLE")

Submission status: Accepted

Solution code:
#### import ####
import sys
sys.setrecursionlimit(10**7)
import math
from collections import defaultdict

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))

#################

S = str(input())
T = str(input())

if len(T)>len(S):
  print('UNRESTORABLE')
  sys.exit()

flag = False
for i in range(len(S)-len(T)+1)[::-1]:
  counter = 0
  for j in range(len(T)):
    if (S[i+j]!='?') and (S[i+j]!=T[j]):
      break
    counter += 1
  if counter == len(T):
    flag = True
    break
  
if flag==False:
  print('UNRESTORABLE')
else:
  S = S[0:i] + T + S[i+len(T):]
  S = S.replace('?', 'a')
  print(S)

Submission status: Accepted

Solution code:
# 辞書順なので後ろから当てはまるように探す
# N<=50なので全探索で構わない
s, t = input(), input()
for si in range(len(s) - len(t), -1, -1):
    flag = True
    for ti in range(len(t)):
        if s[si + ti] != t[ti] and s[si + ti] != "?":
            flag = False
            break
    if flag:
        ans = ""
        for i in range(si):
            if s[i] == "?":
                ans += "a"
            else:
                ans += s[i]
        ans += t
        for i in range(si + len(t), len(s)):
            if s[i] == "?":
                ans += "a"
            else:
                ans += s[i]
        print(ans)
        exit()
print("UNRESTORABLE")

Submission status: Accepted

Solution code:
s=input()
t=input()
u=''
v=[]
count=0

for i in range(len(s)-len(t)+1):
    for j in range(len(t)):
        if t[j]==s[i+j] or s[i+j]=='?':
            count+=1
    if count==len(t):
        for k in range(len(s)):
            if i<=k<=i+len(t)-1:
                u+=t[k-i]
            elif s[k]=='?':
                u+='a'
            else:
                u+=s[k]
                    
                    
        v.append(u)
        u=''
    count=0
if v==[]:
    print('UNRESTORABLE')
else:
    print(min(v))

Submission status: Accepted

Solution code:
#2-2-3-1
S = input()
T = input()
S_rev = list(S[::-1])
T_rev = list(T[::-1])

def check(i,S,T):
    for k in range(len(T)):
        if (S[i+k] == "?" or S[i+k] == T[k]):
            continue
        else:
            return False
    for k in range(len(T)):
        S[i+k] = T[k]
    for j in range(len(S)):
        if S[j] == "?":
            S[j] = "a"
    return S[::-1]

count = 0
for i in range(len(S_rev) - len(T_rev) +1):
    a = check(i,S_rev,T_rev)
    if a:
        a = "".join(a)
        print(a)
        count = 1
        break

if count == 0:
    print("UNRESTORABLE")

Submission status: Accepted

Solution code:
S = input()
T = input()
ls = len(S)
lt = len(T)

for i in range(ls-lt,-1,-1):
  for j in range(lt):
    if S[i+j] != T[j] and S[i+j] != '?':
      break
  else:
    print((S[:i] + T + S[i+lt:]).replace('?','a'))
    break
else:
  print('UNRESTORABLE')

Submission status: Accepted

Solution code:
S = input()
T = input()
len_s = len(S)
len_t = len(T)

for i in range(len_s-len_t, -1, -1):
    for j, t in enumerate(T):
        if t == S[i+j] or S[i+j] == "?":
            pass
        else:
            break
    else:
        ans = list(S)
        ans[i:i+len_t] = T
        print("".join(ans).replace("?","a"))
        exit()

print("UNRESTORABLE")

Submission status: Accepted

Solution code:
S = input()
T = input()
N = len(S)
M = len(T)

for i in range(1,N-M+2):
  count = 0
  for j in range(1,M+1):
    if S[N-i-j+1] == T[M-j] or S[N-i-j+1] == "?":
      count += 1
    else:
      break
  if count == M:
    S = S[:N-i-M+1]+T+S[N-i+1:]
    S = S.replace("?","a")
    print(S)
    exit()
else:
  print("UNRESTORABLE")

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest
import sys
sys.setrecursionlimit(4100000)

import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

import re


def resolve():
    s_prime = sys.stdin.readline().split()[0]
    T = sys.stdin.readline().split()[0]
    logger.debug(s_prime)
    logger.debug(T)

    s_len = len(s_prime)
    t_len = len(T)

    r_s_prime = s_prime[::-1]
    r_t = T[::-1]

    answer = "UNRESTORABLE"
    for i_s, s_char in enumerate(r_s_prime):
        if s_len - i_s >= t_len:
            is_match = True
            for i_t, t_char in enumerate(r_t):
                if r_s_prime[i_s + i_t] == '?' or r_s_prime[i_s +
                                                            i_t] == t_char:
                    pass
                else:
                    is_match = False
                    break

            if is_match:
                answer = r_s_prime[:i_s] + r_t + r_s_prime[i_s + len(r_t):]
                answer = answer[::-1]
                pattern = re.compile(r'\?')
                answer = pattern.sub('a', answer)
                break
        else:
            break

    print(answer)


if __name__ == "__main__":
    resolve()


# AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す
# python -m unittest template/template.py で実行できる
# pypy3 -m unittest template/template.py で実行できる
class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """?tc????
coder"""
        output = """atcoder"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """??p??d??
abc"""
        output = """UNRESTORABLE"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """?
a"""
        output = """a"""
        self.assertIO(input, output)

    def test_入力例_4(self):
        input = """?
ab"""
        output = """UNRESTORABLE"""
        self.assertIO(input, output)

    def test_入力例_5(self):
        input = """??????????
abc"""
        output = """aaaaaaaabc"""
        self.assertIO(input, output)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#ABC76 C

from copy import deepcopy
s = list(input())
t = list(input())

ns = len(s)
nt = len(t)
f1 = 0
for i in range(ns):
    if s[i] in t:
        ind = t.index(s[i])
        for j in range(i-ind,i-ind+nt):
            if j < ns:
                if s[j] == t[j-i+ind] or s[j] == '?':
                    continue
                else:
                    break
            else:
                break
        else:
            f1 = 1
            x = deepcopy(s)
            x[i-ind:i-ind+nt] = t
            break
f2 = 0
for i in range(ns)[::-1]:
    if s[i] == '?':
        for j in range(i,i+nt):
            if j < ns:
                if s[j] == t[j-i] or s[j] == '?':
                    continue
                else:
                    break
            else:
                break
        else:
            f2 = 1
            y = deepcopy(s)
            y[i:i+nt] = t
            break
if f1 & f2:
    for i in range(ns):
        if x[i] == '?':
            x[i] = 'a'
        if y[i] == '?':
            y[i] = 'a'
    x = ''.join(x)
    y = ''.join(y)
    ans = [x,y]
    ans.sort()
    print(ans[0])

elif f1 and not f2:
    for i in range(ns):
        if x[i] == '?':
            x[i] = 'a'
    x = ''.join(x)
    print(x)
elif not f1 and f2:
    for i in range(ns):
        if y[i] == '?':
            y[i] = 'a'
    y = ''.join(y)
    print(y)
else:
    print('UNRESTORABLE')

Submission status: Accepted

Solution code:
S = input()
T = input()

ans = []
for i in range(len(S)-len(T)+1):
    flag = 1
    for j in range(len(T)):
        if S[i+j] == T[j] or S[i+j] == "?":
            continue
        else:
            flag = 0
    if flag == 1:
        S_restore = list(S)
        for j in range(len(T)):
            S_restore[i+j] = T[j]
        for j in range(len(S)):
            if S_restore[j] == "?":
                S_restore[j] = "a"
        ans.append("".join(map(str, S_restore)))
ans.sort()

if len(ans) >= 1:
    print(ans[0])
else:
    print("UNRESTORABLE")

Submission status: Accepted

Solution code:
s=str(input())
t=str(input())
for i in range(len(s)-len(t)+1):
    l=s[len(s)-len(t)-i:len(s)-i]
    if all([l[i]==t[i] or l[i]=="?" for i in range(len(t))]):
        s=s[:len(s)-len(t)-i]+t+s[len(s)-i:]
        break
s=s.replace("?","a")
if t in s:print(s)
else:print("UNRESTORABLE")

Submission status: Accepted

Solution code:
# 文字列S'（s）および文字列Tを入力する
s = input()
T = input()
# Sを設定する（初期状態 =  "UNRESTORABLE"）
S = "UNRESTORABLE"
# |s|が|T|以上である場合に探索する
if len(s) >= len(T):
    # sの|T|文字の部分文字列（s_partial）について探索する
    for i in range(len(s) - len(T) + 1):
        s_partial = s[i:i + len(T)]
        # 部分文字列中のj番目の文字を調べる
        for j in range(len(T)):
            # j番目の文字が"?"でもTのj番目の文字でもない場合、繰り返しを抜ける
            if s_partial[j] not in ("?", T[j]):
                s_partial = None
                break
        if s_partial == None:
            continue
        # sの部分文字列をTに置き換えた文字列をtextとする
        text = s[:i] + T + s[i + len(T):]
        # textの"?"を"a"に置き換える
        text = text.replace("?", "a")
        # Sが初期状態のままである場合、もしくはSよりもtextの方が辞書順で小さい場合
        if S == "UNRESTORABLE" or text < S:
            # Sをtextに更新する
            S = text
# Sを出力する
print(S)

Submission status: Accepted

Solution code:
def solve(S, T):
    for i in range(len(S) - len(T), -1, -1):
        ok = True
        for j in range(len(T)):
            if not (S[i + j] == "?" or S[i + j] == T[j]):
                ok = False
        if ok:
            return S[:i].replace("?", "a") + T + S[i + len(T) :].replace("?", "a")

    return "UNRESTORABLE"


S = input()
T = input()
print(solve(S, T))

Submission status: Accepted

Solution code:
import re
# 文字列S'（s）および文字列Tを入力する
s = input()
T = input()
# sの"?"を"."に置き換え、新たな文字列（pattern）とする
pattern = s.replace("?", ".")
# sとTの長さの差をNとする
N = len(s) - len(T)
# Sを設定する（初期状態 =  "UNRESTORABLE"）
S = "UNRESTORABLE"
# 0〜Nまでの整数iについて繰り返す
for i in range(N + 1):
    # patternの先頭N - i文字をTの先頭につけ、patternの後方i文字をTの後方につけた文字列を作成する（text）
    text = pattern[:N - i] + T + pattern[::-1][:i][::-1]
    # patternが正規表現としてtextに一致するかを調べる
    matchOB = re.match(pattern, text)
    # 一致する場合
    if matchOB:
        # textの"."を"a"に置き換える
        text = text.replace(".", "a")
        # Sが初期状態のままである場合、もしくはSよりもtextの方が辞書順で小さい場合
        if S == "UNRESTORABLE" or text < S:
            # Sを更新する
            S = text
# Sを出力する
print(S)

Submission status: Accepted

Solution code:
S=input()
T=input()
lens=len(S)
lent=len(T)
ans=[]
for i in range(lens-lent+1):
    SS=S[i:i+lent]
    for j in range(len(SS)):
        if SS[j]!=T[j] and SS[j]!="?":
            break
    else:
        SSS=S[:i]+T+S[lent+i:]
        ans.append(SSS.replace("?","a"))
ans.sort()
if ans==[]:
    print("UNRESTORABLE")
else:
    print(ans[0])

Submission status: Accepted

Solution code:
S = input()
lens = len(S)
T = input()
lent = len(T)
if lens < lent:
    print('UNRESTORABLE')
else:
    ii = lens - lent
    while True:
        subs = S[ii:]
        for j in range(lent):
            if subs[j] == '?':pass
            elif subs[j] != T[j]:
                #print('not match',subs,T)
                ii -= 1
                break
        else:
            #print('matched:',ii,subs,T)
            newS = ''
            if ii == 0:newS = T+S[lent:]
            else:newS = S[0:ii] + T + S[ii+lent:]
            print(newS.replace('?','a'))
            break
        if ii < 0:
            print('UNRESTORABLE')
            #print('scan end.','UNRESTORABLE')
            break

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline

S = list(input())
T = list(input())
S.pop()
T.pop()

N = len(S)
M = len(T)

def main():
    store = []
    for i in range(N - M + 1):
        X = S[i:i+M]
        for j in range(M):
            if X[j] != T[j] and X[j] != "?":
                break
        else:
            store.append(i)
        
    if len(store) == 0:
        return 0
    else:
        index = store.pop()
        if index + M == N:
            ans = S[:index] + T
        else:
            ans = S[:index] + T + S[index + M:]

    for i in range(N):
        if ans[i] == "?":
            ans[i] = "a"
    return "".join(ans)

ans = main()
if ans:
    print(ans)
else:
    print("UNRESTORABLE")

Submission status: Accepted

Solution code:
S_ = input()
T = input()
S = "UNRESTORABLE"
for i, s in enumerate(S_):
    if i + len(T) > len(S_):
        break
    for j in range(len(T)):
        if S_[i+j] != T[j] and S_[i+j] != "?":
            break
    else:
        S = S_[:i] + T + S_[i+len(T):]
        S = S.replace("?", "a")
print(S)

Submission status: Accepted

Solution code:
s = input()
t = input()
ls, lt = map(len, [s, t])
for i in range(lt-1, ls)[::-1]:
    if ls < lt:
        break
    flag = 0
    for j in range(lt):
        if s[i-j] == "?":
            continue
        elif s[i-j] != t[lt-1-j]:
            flag = 1
            break
    if flag == 0:
        s = s.replace("?", "a")
        print(s[:i-lt+1]+t+s[i+1:])
        exit()
print("UNRESTORABLE")

Submission status: Accepted

Solution code:
s=input()
t=input()
n=len(s)
m=len(t)
s_list=[]
for i in range(n):
    temp=''
    if n-i>=m:
        for j in range(n):
            if i<=j<=i+m-1:
                if s[j]=='?':
                    temp=temp+t[j-i]
                else:
                    if s[j]==t[j-i]:
                      temp=temp+t[j-i]
                    else:
                        break
            else:
                if s[j]=='?':
                    temp=temp+'a'
                else:
                    temp=temp+s[j]
        else:
            s_list.append(temp)
s_list.sort()
if s_list==[]:
    print('UNRESTORABLE')
else:
    print(s_list[0])

Submission status: Accepted

Solution code:
s = input()
t = input()
ls, lt = map(len, [s, t])
for i in range(lt-1, ls)[::-1]:
    if ls < lt:
        break
    flag = 0
    for j in range(lt):
        if s[i-j] == "?":
            continue
        elif s[i-j] != t[lt-1-j]:
            flag = 1
            break
    if flag == 0:
        s = s.replace("?", "a")
        print(s[:i-lt+1]+t+s[i+1:])
        exit()
print("UNRESTORABLE")

Submission status: Accepted

Solution code:
from sys import stdin
S = (stdin.readline().rstrip())
T = (stdin.readline().rstrip())

def count_match(a,b):
    cnt = 0
    for w1,w2 in zip(a,b):
        if w1 == w2:
            cnt += 1
    return cnt

flag = False
for i in range(len(S)-len(T)+1):
    match = count_match(S[i:i+len(T)],T) + S[i:i+len(T)].count("?")
    if match == len(T):
      flag = True
      ans = S[:i] + T + S[i+len(T):]
      ans = ans.replace("?","a")
if flag:
  print(ans)
else:
  print("UNRESTORABLE")

Submission status: Accepted

Solution code:

S = input()
T = input()


_S = []
for s in S:
    _S.append(ord(s)-97)

_T = []
for t in T:
    _T.append(ord(t)-97)


s_len = len(_S)
t_len = len(_T)
flag = False
buff = 0
for i in range(s_len-t_len+1):
    count = 0
    for j in range(t_len):
        if _S[i+j] == _T[j] or _S[i+j] == -34:
            count += 1
        else:
            continue
    if count >= t_len:
        buff = i
        flag = True
        # break


_buff = []

if not flag:
    print("UNRESTORABLE")
    exit()
else:
    # print("seikou")
    for i in range(t_len):
        _S[buff+i] = _T[i]

for i in range(s_len):
    if _S[i] == -34:
        _S[i] = 0

ans = []

for i in range(s_len):
    ans.append(chr(97+_S[i]))

print(''.join(ans))

Submission status: Accepted

Solution code:
s=input()
t=input()
ls=len(s)
lt=len(t)
S=''
for i in range(ls-lt+1):
    cnt=0
    for j in range(lt):
#        print(s[i+j])
        if s[i+j]==t[j]:
            cnt+=1
        elif s[i+j]=='?':
            cnt+=1
        else:
            break
    if cnt==lt:
        S=s[:i]+t+s[i+lt:]
if S=='':
    print('UNRESTORABLE')
else:
    S=list(S)
    for i in range(ls):
        if S[i]=='?':
            S[i]='a'
    print(''.join(S))

Submission status: Accepted

Solution code:
S = input()
T = input()

def slv(S, T):
    cnd = []
    for i in range(len(S) - len(T) + 1):
        a = ''
        for j in range(len(T)):
            if S[i+j] in ('?', T[j]):
                a += T[j]
                continue
            break
        if len(a) == len(T):
            for j in range(i-1, -1, -1):
                a = ('a' if S[j] == '?' else S[j]) + a
            for j in range(i + len(T), len(S)):
                a += ('a' if S[j] == '?' else S[j])
            cnd.append(a)
    if len(cnd) == 0:
        return 'UNRESTORABLE'
    cnd.sort()
    return cnd[0]

print(slv(S, T))

Submission status: Accepted

Solution code:

s = input()
t = input()


S = list(s)
T = list(t)

S.reverse()
T.reverse()


flag = False

if len(S) < len(T):
    print ("UNRESTORABLE")

else:
    
    for i in range(len(S)-len(T)+1):

        for j in range(len(T)):

            fl2 = True

            if S[i+j] != T[j] and S[i+j] != "?":
                fl2 = False
                break

        if fl2:

            for j in range(len(T)):
                
                flag = True
                S[i+j] = T[j]

            break


    if flag:

        ans = ""

        for i in S:

            if i == "?":
                ans = "a" + ans
            else:
                ans = i + ans


        print (ans)
        
    else:

        print ("UNRESTORABLE")