查找子序列(非连续) [英] Finding subsequence (nonconsecutive)
本文介绍了查找子序列(非连续)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有字符串 needle
并且我想检查它是否作为 haystack
中的 substring 连续存在,我可以使用:>
如果大海捞针:...
在非连续子序列的情况下我可以使用什么?示例:
<预><代码>>>>干草堆 = "abcde12345">>>针1 =ace13">>>针2 =123abc">>>is_subsequence(needle1,干草堆)真的>>>is_subsequence(needle2, haystack) # 顺序很重要!错误的解决方案
不知道有没有内置函数,但是手动做还是比较简单的
def exists(a, b):"""检查b是否作为子序列存在于a中"""位置 = 0对于 ch 中的一个:如果 pos
<预><代码>>>>存在(moo",mo")真的>>>存在(moo",oo")真的>>>存在(哞",哞")错误的>>>存在(干草堆",黑客")真的>>>存在(干草堆",哈希")错误的>>>
If I have string needle
and I want to check if it exists contiguously as a substring in haystack
, I can use:
if needle in haystack:
...
What can I use in the case of a non-continuous subsequence? Example:
>>> haystack = "abcde12345"
>>> needle1 = "ace13"
>>> needle2 = "123abc"
>>> is_subsequence(needle1, haystack)
True
>>> is_subsequence(needle2, haystack) # order is important!
False
解决方案
I don't know if there's builtin function, but it is rather simple to do manually
def exists(a, b):
"""checks if b exists in a as a subsequence"""
pos = 0
for ch in a:
if pos < len(b) and ch == b[pos]:
pos += 1
return pos == len(b)
>>> exists("moo", "mo")
True
>>> exists("moo", "oo")
True
>>> exists("moo", "ooo")
False
>>> exists("haystack", "hack")
True
>>> exists("haystack", "hach")
False
>>>
这篇关于查找子序列(非连续)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文