如何解决如何在字符串中插入丢失的子字符串以使其回文?
比方说,
string1 = "abijkabccbakfgba"
sub_string = "abcd"
我必须确保sub_string
中存在string1
,并找到所有可能的回文而不改变字符串的总长度。
可以使用最少的替换次数对"abcdkabccbakdcba"
进行回文,并确保sub_string
中存在string1
。
我们如何找到最佳解决方案that can handle even larger length of string
?
def func(string1,sub_string):
if string1 == string1[::-1]:
if sub_string in string1:
print("Valid with zero substitutions")
else:
# replace missing substring to make it palindrome
# If portion of sub_string exists,let's continue from there
# If none exists,let's replace any characters to match it to sub_string
else:
# Make it palindrome ensuring sub_string exists with less number of substitutions
有没有更好的方法或任何特定的算法来保持时间复杂度和空间复杂度?
1) Make string1 palindrome.
2) Ensure that sub_string exists in string1.
3) Find the least number substitutions used to make it palindrome.
string1 = "rstutir"
string1 = list(string1)
sub_string = "abc"
count = 0
for i in range(len(string1)//2):
if(string1[i]== string1[n-i-1]):
continue
count += 1
if(string1[i]<string1[n-i-1]):
string1[n-i-1]= string1[i]
else:
string1[i]= string1[n-i-1]
但是,可以通过上述代码实现回文。确保sub_string
中的string1
的最佳方法是什么?
已编辑: 相同的问题Convert given string to Palindrome with given substring
希望您现在能更好地了解问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。