美文网首页
BF算法 C++实现

BF算法 C++实现

作者: 假程序员 | 来源:发表于2019-03-15 01:49 被阅读0次
    //
    //  main.cpp
    //  BF
    //
    //  Created by apple on 2019/3/15.
    //  Copyright © 2019年 apple. All rights reserved.
    //
    
    #include <iostream>
    using namespace std;
    
    int bf(string str, string temp)//返回值是数组下标
    {
        int i = 0;//i,j均是数组下标
        int j = 0;
        while (i<(int)str.length() && j<(int)temp.length())
        {
            if (str[i] == temp[j])//逐个字符进行对比
            {
                i++;
                j++;
            }
            else
            {
                i = i - j;//i回溯
                i = i + 1;//回溯的位置已经失配了,应该从下一个位置重新开始匹配
                j = 0;
            }
        }
        if (j == (int)temp.length())//j超出数组下标范围,即整个temp以完全匹配
        {
            return i - j;//本轮匹配的开始位置
        }
        else
            return -1;//未匹配
    };
    
    
    int main(int argc, const char * argv[]) {
        string str = "asdfghjkl";
        
        cout << bf(str, "as")<<endl;
        cout << bf(str, "fg")<<endl;
        cout << bf(str, "kl")<<endl;
        cout << bf(str, "sk")<<endl;
        return 0;
    }
    
    0
    3
    7
    -1
    Program ended with exit code: 0
    

    相关文章

      网友评论

          本文标题:BF算法 C++实现

          本文链接:https://www.haomeiwen.com/subject/vmrkmqtx.html