BF算法,即暴力(Brute Force)算法,是普通的模式匹配算法,BF算法的思想就是将目标串S的第一个字符与模式串T的第一个字符进行匹配,若相等,则继续比较S的第二个字符和 T的第二个字符;若不相等,则比较S的第二个字符和T的第一个字符,依次比较下去,直到得出最后的匹配结果。BF算法是一种蛮力算法。
Python:
"""BF算法的实现"""
a=[]
a=list(input("请给定一串信息序列:"))
b=[]
b=list(input("请给定一个待查找的串:"))
for i in range(len(a)):
n=0
m=i
for j in range(len(b)):
if a[m]!=b[j]:
n=1
break
m+=1
if n==0:
print(f"找到了,序列开头的索引为{i}")
break
C++:
#include <iostream>
#include <string>
bool bf_search(const std::string& text, const std::string& pattern) {
size_t found = 0;
// 遍历目标字符串,检查模式字符串是否存在
while ((found = text.find(pattern, found)) != std::string::npos) {
++found;
}
// 如果找到匹配,返回true
if (found != std::string::npos) {
return true;
}
// 如果没有找到匹配,返回false
return false;
}
int main() {
// 定义大字符串和大模式字符串
std::string text = "This is a large string that needs to be searched for a pattern.";
std::string pattern = "search";
// 调用BF算法检查大字符串中是否存在大模式字符串
if (bf_search(text, pattern)) {
std::cout << "Pattern found in text." << std::endl;
} else {
std::cout << "Pattern not found in text." << std::endl;
}
return 0;
}