检查在Python中串联给定字符串后是否可以生成给定字符串
假设我们有两个字符串s以及t和r,我们必须检查r=s|。t或r=t+s其中|表示串联。
因此,如果输入类似于s=“world”t=“hello”r=“helloworld”,则输出将为True,因为“helloworld”(r)=“hello”(t)|“世界”。
为了解决这个问题,我们将遵循以下步骤-
如果r的大小与s和t的长度之和不同,则
返回False
如果r以s开头,则
返回True
如果r以t结尾,则
如果r以t开头,则
返回True
如果r以s结尾,则
返回False
让我们看下面的实现以更好地理解-
范例程式码
def solve(s, t, r): if len(r) != len(s) + len(t): return False if r.startswith(s): if r.endswith(t): return True if r.startswith(t): if r.endswith(s): return True return False s = "world" t = "hello" r = "helloworld" print(solve(s, t, r))
输入值
"world", "hello", "helloworld"输出结果
True