BF algorithm (brute force match)

Input of the main string a, b mode

b in a position in

1. Set the relatively subscript i = 0 in a string and the string b, j = 0;

2. repeating the operation until all characters a or b are comparison is completed:

  2.1 If a [i] equals b [i], a and b continue comparing the next pair of characters;

  2.2 is responsible for the subscripts i and j are backtracking, matching the trip begins;

3. If all the characters in b are relatively complete, the match is successful, return to the starting position this trip match; in charge of the match fails, return 0;

#include<iostream>
#define N 100000
using namespace std;
char a[N],b[N];

int the BF ( char A [], char B []) // the BF algorithm 
{
     int I = 0 , J = 0 ; // I, J respectively at variable position of the main string and the pattern string 
    int Start = 0 ; // start recording position of the main string back 
    the while (a [I]! = ' \ 0 ' && B [J]! = ' \ 0 ' )
    {
        if(a[i] == b[j])
        {
            i++;
            j++;
        }
        else
        {
            start++;
            i = start;
            j = 0;
        }
    }
    IF (B [J] == ' \ 0 ' ) // If pattern matching is completed for all the string, i.e. the match is successful, return position 
        return Start + . 1 ;
     the else // Otherwise, the match fails 
        return  0 ;
}

int main ()
{
    int t;
    cin >> t; // t test sample 
    the while (T-- )
    {
        int In Flag; // pattern matching is successful position 
        CIN >> A >> B; // read string 
        In Flag = the BF (A, B);
        cout << flag << endl;
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/biaobiao88/p/11669826.html