检查给定的字符串是否可以通过连接给定的 Python 字符串来生成
假设我们有两个字符串 s 和 t 以及 r,我们需要检查 r 是否等于 s | t 或 r = t + s,其中 | 表示连接。
因此,如果输入类似于 s = "world" t = "hello" r = "helloworld",则输出将为 True,因为 "helloworld" (r) = "hello" (t) | "world" (s)。
为了解决这个问题,我们将遵循以下步骤:
- 如果 r 的大小与 s 和 t 的长度之和不同,则
- 返回 False
- 如果 r 以 s 开头,则
- 如果 r 以 t 结尾,则
- 返回 True
- 如果 r 以 t 结尾,则
- 如果 r 以 t 开头,则
- 如果 r 以 s 结尾,则
- 返回 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP