Finding subsequence (nonconsecutive)

后端 未结 4 914
孤城傲影
孤城傲影 2020-11-29 10:18

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          


        
4条回答
  •  心在旅途
    2020-11-29 11:01

    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
    >>>
    

提交回复
热议问题