21xrx.com
2024-06-03 04:04:44 Monday
登录
文章检索 我的文章 写文章
C++实现BF算法的代码
2023-11-03 15:11:17 深夜i     --     --
C++ BF算法 代码实现

BF算法(Brute-Force Algorithm)是一种简单但有效的字符串匹配算法。它通过从文本串中逐个字符地与模式串进行比较来确定匹配位置。虽然BF算法的时间复杂度为O(n*m),其中n和m分别是文本串和模式串的长度,但由于其实现简单,容易理解和应用,因此仍然被广泛使用。

以下是使用C++实现BF算法的代码示例:


#include <iostream>

#include <string>

using namespace std;

int BFSearch(const string& text, const string& pattern) {

  int n = text.length();

  int m = pattern.length();

  for (int i = 0; i <= n - m; i++) {

    int j;

    for (j = 0; j < m; j++) {

      if (text[i + j] != pattern[j])

        break;

    }

    if (j == m)

      return i;

  }

  return -1;

}

int main() {

  string text;

  string pattern;

  cout << "Enter the text: ";

  getline(cin, text);

  cout << "Enter the pattern: ";

  getline(cin, pattern);

  int index = BFSearch(text, pattern);

  if (index == -1)

    cout << "Pattern not found in the text." << endl;

  else

    cout << "Pattern found at index " << index << " in the text." << endl;

  return 0;

}

以上代码首先定义了一个BFSearch函数,它接受两个参数:文本串text和模式串pattern,并返回模式串在文本串中的位置。在函数中,我们首先获取文本串和模式串的长度n和m。然后通过两层循环进行比较,外层循环控制文本串中的起始位置i,内层循环用于逐个字符地比较文本串和模式串的对应位置。如果两个字符不相等,内层循环会中断,继续外层循环的下一次迭代。如果内层循环完成后j等于模式串长度m,则说明找到了匹配位置,返回对应的起始位置i。如果外层循环结束后仍未找到匹配位置,则返回-1。

在main函数中,我们从用户输入中获取文本串和模式串,并调用BFSearch函数来查找模式串在文本串中的位置。如果返回值为-1,则打印未找到模式串的提示信息。否则,打印找到模式串的位置。

总体而言,以上代码演示了C++实现BF算法的过程。通过逐个字符地比较文本串和模式串,BF算法能够有效地找到匹配位置。尽管时间复杂度较高,但在某些场景下,BF算法仍然是一种可行且简单易用的字符串匹配方案。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复