【问题标题】:Extract a substring that is common in ending of first string and beginning of second string提取常见于第一个字符串结尾和第二个字符串开头的子字符串
【发布时间】:2021-04-01 12:40:16
【问题描述】:

给定 2 个字符串

例如: "Hello World""World Is Awesome"

这不完全是联合。我需要提取一个常见于第一个字符串结尾和第二个字符串开头的子字符串。

在上面的示例中,它将是"World",因为第一个字符串以这个字符列表结尾,第二个字符串以它开头。

最有效的方法是什么?可以是任何语言,但我主要对 python 和 c# 感到好奇。

这是我的解决方案

def union_chars(head, tail):
    match = None
    for i in range(len(head)):
        if tail.startswith(head[-i:]):
            match = head[-i:]
    return match

【问题讨论】:

  • 你能证明自己任何努力解决这个问题吗?
  • 是的,我也应该粘贴我的努力。

标签: python c# string substring


【解决方案1】:

以下是使用for 循环和索引的方法:

def union_chars(head, tail):
    for i in range(len(head)):
        if tail.startswith(head[i:]):
            return head[i:]

print(union_chars("Hello World", "World Is Awesome"))

输出:

World

解释:

首先,遍历head字符串的每个索引, 并检查tail 字符串是否以head 字符串的索引开始到head 字符串的结尾。模板

【讨论】:

  • 谢谢你,安。非常感谢!
  • 但是,当列表之一中只有一个字符时,这也不起作用。喜欢aba
  • @Pol 已修复。-
【解决方案2】:

这是一个基于 Ann Zen 答案的简化解决方案。我认为它的效率更高一些,因为它不需要多次使用len()。而且更短

def union_chars(head, tail):
    match = None
    for i in range(len(head)):
        if tail.startswith(head[-i:]):
            match = head[-i:]
    return match

【讨论】:

  • 实际上,我的解决方案效率明显更高。您可以使用time.perf_counter 对其进行测试。
猜你喜欢
  • 2013-05-21
  • 2018-12-13
  • 2020-02-14
  • 2018-04-23
  • 1970-01-01
  • 2017-04-18
  • 2020-07-02
  • 1970-01-01
  • 2010-12-28
相关资源
最近更新 更多