Python | Merging two strings with Suffix and Prefix
Given two strings A and B and these strings contain lower case letters. The task is to tell the length of the merged strings. For example, given A is “abcde” and B is “cdefg”, then merging the two strings results in “abcdefg”. The merge operation is performed in such a manner that the joining characters are both the suffix of A and Prefix of B. Before merging you are allowed to do any ONE of the following operations:
- Reverse string A
- Reverse string B
Examples:
Input :
A = "ababc"
B = "bcabc"
Output :
Length is 8
the suffix of string A i.e "bc" and prefix of B i.e "bc" is the same
so the merged string will be "ababcabc" and length is 8.
Input :
A = "cdefg"
B = "abhgf"
Output :
Length is 8
the suffix of string A i.e "fg" and prefix of reversed B i.e "fg" is the same
so the merged string will be "cdefghba" and length is 8
Input :
A = "wxyz"
B = "zyxw"
Output :
Length is 4
Below is the Python code implementation of the above mentioned approach.
Python3
def mergedstring(x, y) :
k = len (y)
for i in range ( len (x)) :
if x[i:] = = y[:k] :
break
else :
k = k - 1
return len (a + b[k:])
def merger(a, b):
b1 = b[:: - 1 ]
r1 = mergedstring(a, b)
r2 = mergedstring(a, b1)
if r1 > r2 :
print ("Length is ", r2)
else :
print ("Length is ", r1)
a = "abcbc"
b = "bcabc"
merger(a, b)
|
Output:
Length is 8
Time complexity: O(n^2) where n is the length of the longer string between a and b.
Auxiliary space: O(1) as we are not using any data structures to store intermediate results.
Last Updated :
22 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...