将字符串标记为所需的结果

时间:2018-10-04 19:31:55

标签: python string algorithm

所以,我在看以下问题: Optimal way to "stamp" string into desired string

我受到启发,决定尝试解决该问题。但是,我无法解决。我的代码没有通过所有测试用例(顺便说一下,它们都是隐藏的)。它通过了大约80%的案例。

如果任何人都可以在此处发现错误或提出错误答案的测试用例,我将非常感谢。这可能不是发布此内容的正确位置,但是在代码审阅时,他们不接受逻辑不完全的代码。

我的算法 我遵循与Quiti相同的逻辑,但是做了一些改进。例如,我检查是否可以按照规则放置邮票。尽管如此,我还是从在线法官那里得到了一些错误的答案。

import sys

desiredString = input() #Dynamic
stamp = input()
stampingSpots = []

if (len(set(desiredString)) != len(set(stamp)) or stamp[0] != desiredString[0] or stamp[-1] != desiredString[-1]):
    print("-1")
    sys.exit()
#The task is impossible

def searchAndReplace(stringToFind, howManyLettersMissingFromStart, howManyLettersMissingFromEnd):
    global desiredString
    for x in range(0, len(desiredString)-len(stringToFind)+2): #Limited not to exceed right border
        if desiredString[x:x+len(stringToFind)] == stringToFind:
            if x+1-howManyLettersMissingFromStart <= 0: #The left part of the stamp is out of bounds
                break

            for i in desiredString[x-howManyLettersMissingFromStart:x]:
                if i != "?": #The stamping would overstamp some earlier stamp
                    return False
            for j in desiredString[x-howManyLettersMissingFromStart+len(desiredString):x-howManyLettersMissingFromStart+len(desiredString)+howManyLettersMissingFromEnd]: #Overstamp
                if j != "?":
                    return False

            stampingSpots.append(x+1-howManyLettersMissingFromStart)
            beginning = desiredString[:x]
            beginning += len(stringToFind)*"?"
            beginning += desiredString[len(beginning):]
            desiredString = beginning
            #Replace the string in desiredString with "?" meaning that it is ok
            return True
    return False



#Go through all contiguous subarrays of length
length = len(stamp)
while(length > 0):
    for beginning in range(0, len(stamp)-length+1): #Go through all contigious subarrays with length length
        end = beginning+length
        while(searchAndReplace(stamp[beginning:end], beginning, len(stamp)-length-beginning)):
            searchAndReplace(stamp[beginning:end], beginning, len(stamp)-length-beginning)
    if len(stampingSpots) > 10*len(desiredString):
        print("-1")
        sys.exit()
    length -= 1


if desiredString == len(originalStringToFind)*"?": #All good
    print(len(stampingSpots))
    for i in reversed(stampingSpots):
        print(i, end = " ")
else: #Didn't find it...
    print("-1")

0 个答案:

没有答案