Let's say,
string1 = "abijkabccbakfgba"
sub_string = "abcd"
I have to ensure that sub_string
is present in string1
and find all possible available palindromes without altering overall length of string.
Palindrome can be made to "abcdkabccbakdcba"
, with minimum number of substitutions and ensuring provided sub_string
exists in string1
.
How can we find optimal solution 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
Any better approach or any specific algorithm keeping time complexity and space complexity ?
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]
However palindrome can be achieved by above code. What's best way to ensure sub_string
in string1
?
EDITED: Same question Convert given string to Palindrome with given substring
Hope you get better view of question now.