如何检查子字符串是否以相同顺序存在于父字符串中

How to check if the substring is present in the parent string in same order

输入

Indian
3
nda
dan
ndani

输出

True
True
False

说明 第一行是父字符串 第二行是测试用例的数量 接下来的 n 行是查询

第一个和第二个查询子字符串的顺序与父字符串中的顺序相同。

对于每个查询,在查询字符串的开头初始化一个指针,仅当您在遍历父字符串时匹配父字符串中的字母时才递增它

start = 0
for x in parent:
    if x == query[start]:
        start += 1
        if start == len(query):
            print(True)
            break
else:
    print(False)

您可以为每个查询执行此操作。

您只需要根据从 i 到结尾的主字符串索引检查每个字符。 你可以试试这个:

main_str = 'Indian'
words = ['nda','dan','ndani']

for word in words:
    checker = []

    for i in range(len(main_str)):
        if i == len(word):
            break

        if word[i] in main_str[i::]:
            checker.append('True')
        else:
            checker.append('False')

    if 'False' in checker:
        print('False')
    else:
        print('True')

它不是非常高效和直观,但它可以完成工作(我认为)。您只需修改代码以适合您的输入

您可以通过从您尝试匹配的子字符串创建一个正则表达式来做到这一点。例如,对于第一个测试用例,如果您想知道 'nda' 是否可以在 'Indian' 中找到,则形成正则表达式 n.*d.*a 并在 [=18] 中搜索该表达式=]:

import re

string = 'Indian'
substrings = [
    'nda',
    'dan',
    'ndan1'
]

for substring in substrings:
    rex = '.*'.join(re.escape(ch) for ch in substring) # 'n.*d.*a'
    print('True' if re.search(rex, string) else 'False')

打印:

True
True
False

这是一个非常简单的程序。但它会起作用 -

string = 'Indian'
words = ['3','nda','dan','ndani']

for sub in words:
    if sub in the string:
       return True
    else:
       return False

这是我的方法 - 使用 iter.

def isSubsequence(sub: str, orig: str) -> bool:

    it = iter(orig)            # 

    return all(ch in orig for ch in sub)


if __name__ == '__main__':
    sub =  'rice'
    orig =  'practice'

    assert isSubsequence(sub, orig)   == True
    assert isSubsequence('pace', orig)  == True
    assert isSubsequence('acts', orig)  == False