c++ 20 字符串快速搜索
C++20中引入了std::boyer_moore_searcher和std::boyer_moore_horspool_searcher两个搜索器,可以用于快速搜索字符串。
std::boyer_moore_searcher使用Boyer-Moore算法实现,时间复杂度为O(n+m),其中n为文本长度,m为模式串长度。
std::boyer_moore_horspool_searcher使用Boyer-Moore-Horspool算法实现,时间复杂度为O(n),其中n为文本长度。
下面是一个使用std::boyer_moore_searcher进行字符串搜索的示例:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string text = "Hello World!";
std::string pattern = "World";
auto searcher = std::boyer_moore_searcher(
pattern.begin(), pattern.end());
auto result = std::search(
text.begin(), text.end(), searcher);
if (result != text.end()) {
std::cout << "Pattern found at position "
<< std::distance(text.begin(), result)
<< std::endl;
} else {
std::cout << "Pattern not found" << std::endl;
}
return 0;
}
输出:
Pattern found at position 6
下面是一个使用std::boyer_moore_horspool_searcher进行字符串搜索的示例:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string text = "Hello World!";
std::string pattern = "World";
auto searcher = std::boyer_moore_horspool_searcher(
pattern.begin(), pattern.end());
auto result = std::search(
text.begin(), text.end(), searcher);
if (result != text.end()) {
std::cout << "Pattern found at position "
<< std::distance(text.begin(), result)
<< std::endl;
} else {
std::cout << "Pattern not found" << std::endl;
}
return 0;
}
输出:
Pattern found at position 6
原文地址: https://www.cveoy.top/t/topic/sFZ 著作权归作者所有。请勿转载和采集!