Runtime of python's if substring in string

前端 未结 4 551
名媛妹妹
名媛妹妹 2020-12-05 18:43

What is the big O of the following if statement?

if \"pl\" in \"apple\":
   ...

What is the overall big O of how python determ

4条回答
  •  温柔的废话
    2020-12-05 19:25

    The time complexity is O(N) on average, O(NM) worst case (N being the length of the longer string, M, the shorter string you search for).

    The same algorithm is used for str.index(), str.find(), str.__contains__() (the in operator) and str.replace(); it is a simplification of the Boyer-Moore with ideas taken from the Boyer–Moore–Horspool and Sunday algorithms.

    See the original stringlib discussion post, as well as the fastsearch.h source code; the base algorithm has not changed since introduction in Python 2.5 (apart from some low-level optimisations and corner-case fixes).

    The post includes a Python-code outline of the algorithm:

    def find(s, p):
        # find first occurrence of p in s
        n = len(s)
        m = len(p)
        skip = delta1(p)[p[m-1]]
        i = 0
        while i <= n-m:
            if s[i+m-1] == p[m-1]: # (boyer-moore)
                # potential match
                if s[i:i+m-1] == p[:m-1]:
                    return i
                if s[i+m] not in p:
                    i = i + m + 1 # (sunday)
                else:
                    i = i + skip # (horspool)
            else:
                # skip
                if s[i+m] not in p:
                    i = i + m + 1 # (sunday)
                else:
                    i = i + 1
        return -1 # not found
    

    as well as speed comparisons.

提交回复
热议问题