4

为了在字符串中找到子字符串的位置,简单的算法需要O(n^2)时间。然而,使用一些高效的算法(例如KMP 算法),这可以在 O(n) 时间内实现:

s = 'saurabh'
w = 'au'

def get_table():
    i = 0; j = 2 
    t = []
    t.append(-1); t.append(0)
    while i < len(w):
        if w[i] == w[j-1]:
            t.append(j+1)
            j += 1
        else:
            t.append(0)
            j = 0 
        i += 1
    return t

def get_word():
    t = get_table()
    i = j = 0 
    while i+j < len(s):
        if w[j] == s[i+j]:
            if j == len(w) - 1:
                return i
            j += 1
        else:
            if t[j] > -1: 
                i = i + j - t[j]
                j = t[j]
            else:
                i += 1
    return -1

if __name__ == '__main__':
    print get_word()

但是,如果我们这样做:'saurabh'.index('ra'),它是在内部使用一些有效的算法来计算O(n)它还是使用复杂的简单算法O(n^2)

4

3 回答 3

4

在那篇文章 [1] 中,作者详细介绍了算法并对其进行了解释。来自文章:

The function “fastsearch” is called. It is a mix between 
Boyer-Moore and Horspool algorithms plus couple of neat tricks.

并且来自 Boyer–Moore–Horspool 算法 [2] 的 wiki 页面:

The algorithm trades space for time in order to obtain an 
average-case complexity of O(N) on random text, although 
it has O(MN) in the worst case, where the length of the 
pattern is M and the length of the search string is N.

希望有帮助!

[1] http://www.laurentluce.com/posts/python-string-objects-implementation

[2] https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm

于 2016-04-26T15:07:21.877 回答
0

它是几种算法的组合——看看这个

Python字符串'in'运算符实现算法和时间复杂度

或这个

http://effbot.org/zone/stringlib.htm

于 2016-04-26T15:03:16.517 回答
0

有时你可以通过尝试得到一个快速的答案

>>> timeit.timeit('x.index("ra")', setup='x="a"*100+"ra"')
0.4658635418727499
>>> timeit.timeit('x.index("ra")', setup='x="a"*200+"ra"')
0.7199222409243475
>>> timeit.timeit('x.index("ra")', setup='x="a"*300+"ra"')
0.9555441829046458
>>> timeit.timeit('x.index("ra")', setup='x="a"*400+"ra"')
1.1994099491303132
>>> timeit.timeit('x.index("ra")', setup='x="a"*500+"ra"')
1.4850994427915793
于 2016-04-26T19:26:04.597 回答