检查Python中字符串是否可以通过递归删除给定子字符串变为空
假设我们有两个字符串 s 和 t。我们可以任意次数地从 s 中删除 t。并且 t 每次只出现一次。我们必须检查 s 是否可以通过尽可能多次删除 t 而变为空。
因此,如果输入类似于 s = "pipipinnn" t = "pin",则输出将为 True,因为我们可以从 "pipipinnn" 中删除 "pin",然后我们将得到 "pipinn",再次删除 "pin" 以获得字符串 "pin",然后将其删除以使其为空。
为了解决这个问题,我们将遵循以下步骤:
- 当 s 的大小 > 0 时,执行
- position := t 在 s 中的起始索引
- 如果 position 不在 s 中,则
- 退出循环
- s := 从 s 中删除一次 t
- 当 s 的大小等于 0 时返回 true,否则返回 false
让我们看看以下实现以获得更好的理解:
示例
def solve(s, t): while len(s) > 0: position = s.find(t) if position == -1: break s = s.replace(t, "", 1) return len(s) == 0 s = "pipipinnn" t = "pin" print(solve(s, t))
输入
"pipipinnn", "pin"
输出
True
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP