????????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=0m=ifor j in range(len(b)):if a[m]!=b[j]:n=1breakm+=1if 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;}// 如果找到匹配,返回trueif (found != std::string::npos) {return true;}// 如果沒有找到匹配,返回falsereturn 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;
}