For faster navigation, this Iframe is preloading the Wikiwand page for 字串搜尋演算法.

字串搜尋演算法

字串搜尋演算法String searching algorithms)又稱字串比對演算法string matching algorithms)是一种搜索算法,是字串演算法中的一類,用以試圖在一長字符串或文章中,找出其是否包含某一個或多個字符串,以及其位置。

最直觀的解法是比對,如下例中,在字符串haystack中找出字符串needle

char* haystack;
char* needle;
int hlen, nlen, found;
int i,j,k;

found = 0;
hlen = strlen(haystack);
nlen = strlen(needle);
for (i = 0; i < hlen; ++i) {
    for (j = 0; j < nlen; ++j) {
        if (haystack[i+j] != needle[j]) break;
        if (j == nlen - 1) found = 1;
    };
};
return found;

上例中,若字符串needle存在於字符串haystack中,則傳回1,否則傳回0。

但是此直觀算法的複雜度為 O(mn),其中haystack的長度為n、needle的長度為m,所以另有更快速的算法。

部分算法比较

[编辑]

m 为模式的长度, n 为要搜索的字符串长度, k为字母表长度。

算法 预处理时间 匹配时间
朴素算法 0 (无需预处理) Θ(nm)
Rabin-Karp算法 Θ(m) 平均 Θ(n + m),
最差 Θ((n−m)m)
基于有限状态机的搜索 Θ(mk) Θ(n)
克努斯-莫里斯-普拉特算法 Θ(m) Θ(n)
Boyer-Moore字符串搜索算法 Θ(m + k) 最好Ω(n/m),
最坏 O(n)
Bitap算法 Θ(m + k) O(mn)

外部連結

[编辑]
{{bottomLinkPreText}} {{bottomLinkText}}
字串搜尋演算法
Listen to this article

This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:

This article was just edited, click to reload
This article has been deleted on Wikipedia (Why?)

Back to homepage

Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}

Install Wikiwand

Install on Chrome Install on Firefox
Don't forget to rate us

Tell your friends about Wikiwand!

Gmail Facebook Twitter Link

Enjoying Wikiwand?

Tell your friends and spread the love:
Share on Gmail Share on Facebook Share on Twitter Share on Buffer

Our magic isn't perfect

You can help our automatic cover photo selection by reporting an unsuitable photo.

This photo is visually disturbing This photo is not a good choice

Thank you for helping!


Your input will affect cover photo selection, along with input from other users.

X

Get ready for Wikiwand 2.0 🎉! the new version arrives on September 1st! Don't want to wait?