首页 > 解决方案 > 检查像 '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

标签: pythonstringloopsmethodsfind

解决方案


假设您正在检查一个字符串是否是另一个字符串的子序列。

# 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

推荐阅读