用 Python 编写程序检查一个字符串是否可以通过删除一个元素转换为另一个字符串
pythonserver side programmingprogramming更新于 2026/1/12 19:24:17
假设我们有两个字符串 s 和 t,我们必须检查是否可以通过从 s 中删除 1 个字母来获得 t。
因此,如果输入为 s = "world", t = "wrld",则输出将为 True。
为了解决这个问题,我们将遵循以下步骤 −
- i:= 0
- n:= size of s
- while i < n,执行
- temp:= s 的子字符串[从索引 0 到 i-1] 连接 s 的子字符串[从索引 i+1 到结尾]
- 如果 temp 与 t 相同,则
- 返回 True
- i := i + 1
- 返回 False
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, s, t): i=0 n=len(s) while(i<n): temp=s[:i] + s[i+1:] if temp == t: return True i+=1 return False ob = Solution() s = "world" t = "wrld" print(ob.solve(s, t))
输入
"world", "wrld"
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

