用 Python 编写程序,从两个字符串创建词汇最小的字符串

pythonserver side programmingprogramming更新于 2025/12/17 9:16:17

假设我们有两个字符串。我们想从这些字符串中创建一个词汇最小的字符串。为了创建字符串,我们比较两个字符串的第一个字母,并从其中一个字符串中提取词汇较小的字母。如果出现平局,即字母相同;我们从第一个字符串中提取字母。我们重复此过程,直到两个字符串都为空。必须返回构造的最小字符串。

因此,如果输入为 input_1 = 'TUTORIALS', input_2 = 'POINT',则输出将是 POINTTUTORIALS

如果我们比较这两个字符串,我们会得到这个逐步 −

TUTORIALS POINT
TUTORIALS OINT = P
TUTORIALS INT = PO
TUTORIALS NT = POI
TUTORIALS T = POIN
TUTORIALS = POINT

由于其中一个字符串为空,因此整个第一个字符串现在被放置在结果最小字符串中。因此,最终的字符串是 POINTTUTORIALS。

为了解决这个问题,我们将遵循以下步骤 −

  • input_1 := input_1 + "z"
  • input_2 := input_2 + "z"
  • temp_1 := 0
  • temp_2 := 0
  • res_str := 空白字符串
  • 当 temp_1 < input_1 的大小且 temp_2 < input_2 的大小时,执行
    • 如果 input_1[从索引 temp_1 到字符串末尾] < input_2[从索引 temp_2 到字符串末尾],则
      • res_str := res_str + input_1[temp_1]
      • temp_1 := temp_1 + 1
    • 否则,
      • res_str := res_str + input_2[temp_2]
      • temp_2 := temp_2 + 1
  • res_str := res_str[从索引 0 到字符串的倒数第二个元素]
  • 如果 temp_1 < (input_1) 的长度,则
    • res_str := res_str + input_1[从索引 temp_1 到字符串的倒数第二个元素]
  • 如果 temp_2 < (input_2) 的长度,则
    • res_str := res_str + input_2[从索引 temp_2 到字符串的倒数第二个元素]
  • 返回 res_str

示例

让我们看看下面的实现以便更好地理解 −

def solve(input_1, input_2):
   input_1 += "z"
   input_2 += "z"
   temp_1 = 0
   temp_2 = 0
   res_str = ""
   while temp_1 < len(input_1) and temp_2 < len(input_2):
      if input_1[temp_1:] < input_2[temp_2:]:
         res_str += input_1[temp_1]
         temp_1 += 1
      else:
         res_str += input_2[temp_2]
         temp_2 += 1
   res_str = res_str[:-1]
   if temp_1 < len(input_1):
      res_str += input_1[temp_1:-1]
   if temp_2 < len(input_2):
      res_str += input_2[temp_2:-1]
   return res_str

print(solve('TUTORIALS', 'POINT'))

输入

'TUTORIALS', 'POINT'

输出

POINTTUTORIALS

相关文章


有用资源