检查类似“hello”的字符串是否是另一个字符串的子序列

2024-09-30 06:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,这是一个我们给它一个输入的问题

ahhellllloou

如果在示例中可以删除一些字母或忽略它们,最后我们到达hello,则必须print('YES') else print('NO')例如:

input = 'ahhellllloou' output = 'YES' input = 'hlelo' output = 'NO'-因为在这个输入中我们无法找到hello单词,所以它是hlelo不是hello

另一个例子是'hezzrtlilo',我们可以删除zzrt和我,然后看到“hello”,在这种情况下,答案必须是真的,因为最后我们看到hello

另一个例子:input = 'tymbzjyqhymedasloqbq' output = 'NO'-因为在这个输入中,我们可以到达helo,它有一个l而不是两个ll


Tags: no示例helloinputoutput字母单词else
1条回答
网友
1楼 · 发布于 2024-09-30 06:11:11

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

# 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

相关问题 更多 >

    热门问题