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:

  1. Reverse string A
  2. 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# function to find the length of the
# merged string
  
def mergedstring(x, y) :
      
    k = len(y)
    for i in range(len(x)) :
          
        if x[i:] == y[:k] :
            break
        else:
            k = k-1
  
    # uncomment the below statement to
    # know what the merged string is
    # print(a + b[k:])
    return len(a + b[k:])
  
# function to find the minimum length
# among the  merged string
def merger(a, b):
    # reverse b 
    b1 = b[::-1
  
    # function call to find the length
    # of string without reversing string 'B'
    r1 = mergedstring(a, b)
  
    # function call to find the length
    # of the string by reversing string 'B'
    r2 = mergedstring(a, b1)
  
    # compare between lengths
    if r1 > r2 :
        print("Length is", r2)
    else :
        print("Length is", r1)
              
# driver code
a = "abcbc"
b = "bcabc"
  
merger(a, b)

chevron_right


Output:

Length is 8



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.