The Boyermoore string search algorithm returns the start position of the first occurrence of pat in TXT, returns 1 if not present, the algorithm is O (n), the worst is O (m*n) (M, N is the length of Pat and TXT respectively).
1#include <vector>2#include <list>3#include <map>4#include <Set>5#include <queue>6#include <deque>7#include <stack>8#include <bitset>9#include <algorithm>Ten#include <functional> One#include <numeric> A#include <utility> -#include <sstream> -#include <iostream> the#include <iomanip> -#include <cstdio> -#include <cmath> -#include <cstdlib> +#include <ctime> -#include <cstring> +#include <string> A at using namespacestd; - - #defineSZ (a) int ((a). Size ()) - #definePB Push_back - - in classBoyermoore { - Private: to intR; + stringPat; -vector<int> right;//The bad-character Skip Array the * Public: $Boyermoore (string_pat,int_r = the) {Panax NotoginsengPat =_pat; -R =_r; theright = vector<int> (R,-1); + A for(inti =0; I < SZ (PAT); ++i) { theRight[pat[i]] =i; + } - } $ $ - //return offset of first match;-1 if no match - intSearchstringtxt) { the intM =SZ (PAT); - intN =sz (TXT);Wuyi intSkip; the for(inti =0; I <= n-m; i + =Skip) { -Skip =0; Wu for(intj = m1; J >=0; j--) { - if(Pat[j]! = txt[i+J]) { AboutSkip = Max (1, j-right[txt[i+J]]); $ Break; - } - } - if(Skip = =0)returnI//found A } + return-1;//Not found the } - $ }; the the the intMain () { the stringtxt, Pat; -CIN >>txt; inCIN >>Pat; the theBoyermoore *obj =NewBoyermoore (PAT); About intpos = obj->search (TXT); the thecout << POS <<Endl; the + - Delete obj; the return 0;Bayi}
Boyermoore string Search algorithm