📜  Python|使用后缀和前缀合并两个字符串

📅  最后修改于: 2022-05-13 01:54:23.044000             🧑  作者: Mango

Python|使用后缀和前缀合并两个字符串

给定两个字符串AB ,这些字符串包含小写字母。任务是告诉合并字符串的长度。例如,假设A 是“abcde”B 是“cdefg” ,那么合并这两个字符串会得到“abcdefg”。合并操作以这样一种方式执行,即连接字符既是A 的后缀,是 B 的前缀
在合并之前,您可以执行以下任何一项操作:

  1. 反转字符串A
  2. 字符串B

例子:

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

下面是上述方法的Python代码实现。

# 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)

输出:

Length is 8