python字符串添加字符边框_python-将字符串“标记”为所需字符串的最佳方法

因此,我正在寻找以下问题的算法:

系统会为您提供所需的字符串s和标记t. t也是一个字符串.令开始的字符串为len *(s)*“?”.

是否可以使用戳记使用戳记将起始字符串转换为字符串s?整个图章必须位于开头的字符串内(图章的边界不得超过????? …字符串的边界).

打印所需数量的图章,并为每个图章打印图章的左边框.

例:

AABCACA (desired result)

ABCA (stamp)

Solution:

3

1 4 2

explanation: ??????? → ABCA??? → ABCABCA → AABCACA.

我的解决方案:

如果图章的首字母不是所需字符串的首字母,则无法执行此任务.最后一个字母也是如此.如果戳记未在所需字符串中包含所有字母,则该任务是不可能的.

我的算法是这样的:尝试在所需的字符串中找到图章.如果找到它,请将其删除并用问号替换.标记图章的左边框.尽可能做到这一点.

然后寻找大小为len(stamp)-1的图章的连续子数组.如果发现其中任何一个,请将其删除并替换为问号.标记图章的左边框.

然后寻找大小为len(stamp)-2的图章的连续子数组.如果发现其中任何一个,请将其删除并替换为问号.标记图章的左边框.这样做直到完成.那里您有答案.

问题所在

我不确定我的代码有什么问题,因为它似乎无法通过一些测试用例.可能存在逻辑错误.

import sys

desiredString = input()

stamp = input()

stampingSpots = []

if (len(set(desiredString)) != len(set(stamp)) or stamp[0] != desiredString[0] or stamp[-1] != desiredString[-1]):

print("-1")

sys.exit()

def searchAndReplace(stringToFind, fix): #Search for stringToFind and replace it with len(stringToFind)*"?". Fix is used to fix the position.

global desiredString

for x in range(0, len(desiredString)-len(stringToFind) 1):

if desiredString[x:x len(stringToFind)] == stringToFind:

stampingSpots.append(x 1-fix) #Mark down the stamping spot

firstPart = desiredString[:x]

firstPart = len(stringToFind)*"?"

firstPart = desiredString[len(firstPart):]

desiredString = firstPart

return True

return False

while(searchAndReplace(stamp,0)): #Search for the full stamp in desiredString

searchAndReplace(stamp,0)

length = len(stamp)-1

while(length > 0):

for firstPart in range(0, len(stamp)-length 1):

secondPart = firstPart length

while(searchAndReplace(stamp[firstPart:secondPart], firstPart)):

searchAndReplace(stamp[firstPart:secondPart], firstPart)

if len(stampingSpots) > 10*len(desiredString): #Too much output, not possible

print("-1")

sys.exit()

length -= 1

print(len(stampingSpots))

for i in reversed(stampingSpots):

print(i, end = " ")

解决方法:

您描述的算法从根本上来说是有缺陷的.它产生的结果与图章实际可以做的事情完全不符.例如,对于图章AB和字符串AAA,它将尝试在字符串的边界之外盖章以应用最终的A.它还将尝试将图章ABC的AB和BC子字符串彼此紧挨着使用.字符串ABBC,但没有实际应用的邮票可以做到这一点.

该图章不能用于应用图章字符串的任意子字符串.它可以用于在以前的图章应用程序上盖章,但是您的算法没有考虑过盖章的全部复杂性.同样,即使您可以标记图章字符串的任意子字符串,也没有证明算法会最小化图章应用程序.来源:https://www.icode9.com/content-1-519001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值