python - 检查像 'hello' 这样的字符串是否是另一个字符串的子序列
问题描述
例如,这是一个问题,我们给它一个输入
ahhellllloou
如果可以在示例中删除一些字母或忽略它们,最后我们hello
必须达到它print('YES') else print('NO')
,例如:
input = 'ahhellllloou' output = 'YES' input = 'hlelo' output = 'NO'
- 因为在这个输入中我们无法到达你好这个词它hlelo
不是你好
其他例子是'hezzrtlilo'
我们可以删除zzrt
的,我看到“你好”,在这种情况下,答案必须是真的,因为最后我们看到你好
另一个例子:input = 'tymbzjyqhymedasloqbq' output = 'NO'
- 因为在这个输入中,我们可以到达 helo,它有一个 l 而不是两个 ll
解决方案
假设您正在检查一个字符串是否是另一个字符串的子序列。
# From https://www.geeksforgeeks.org/given-two-strings-find-first-string-subsequence-second/
def isSubSequence(string1, string2, m = None, n = None):
m = len(string1) if m == None else m
n = len(string2) if n == None else n
# Base Cases
if m == 0: return True
if n == 0: return False
# If last characters of two strings are matching
if string1[m-1] == string2[n-1]:
return isSubSequence(string1, string2, m-1, n-1)
# If last characters are not matching
return isSubSequence(string1, string2, m, n-1)
测试
tests = [ 'ahhellllloou' , 'hlelo']
for t in tests:
response = "YES" if isSubSequence("hello", t) else "NO"
print(f'Test Word {t} checks as {response}')
输出
Test Word ahhellllloou checks as YES
Test Word hlelo checks as NO
推荐阅读
- python - 如何获取新创建记录的ID-Postgresql-Flask?
- python - 在 spaCy 中找到最长的和链
- javascript - NestJS项目转换前端到后端
- python - PySyde2 / fbs 冻结 / 无法执行脚本 main
- r - 当时间序列较短且季度数据出现峰值时可能的预测算法
- python - 基于治疗组显示的表单域
- weblogic - Weblogic 12.2.1 应用服务器 JDK 11 支持
- typo3 - 通过来自 Extbase 的 PHP API 调用验证 FrontendUser
- linux - 简化命令行的linux别名
- python - pygsheets - 使用 dotenv 而不是 json 文件