码迷,mamicode.com
首页 > 编程语言 > 详细

BoyerMoore字符串搜索算法

时间:2015-01-18 15:35:44      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

BoyerMoore 字符串搜索算法,返回pat在txt中第一次出现的起始位置,若不存在则返回-1,算法复杂度为O(N), 最坏为O(M*N) (M、N分别为pat与txt的长度)。

 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>
10 #include <functional>
11 #include <numeric>
12 #include <utility>
13 #include <sstream>
14 #include <iostream>
15 #include <iomanip>
16 #include <cstdio>
17 #include <cmath>
18 #include <cstdlib>
19 #include <ctime>
20 #include <cstring>
21 #include <string>
22 
23 using namespace std;
24 
25 #define sz(a) int((a).size())
26 #define pb push_back
27 
28 
29 class BoyerMoore {
30 private:
31     int R;
32     string pat;
33     vector<int> right;     // the bad-character skip array
34 
35 public:
36     BoyerMoore(string _pat, int _R = 256) {
37         pat = _pat;
38         R = _R;
39         right = vector<int> (R, -1);
40         
41         for (int i = 0; i < sz(pat); ++i) {
42             right[pat[i]] = i;
43         }
44     }
45     
46     
47     // return offset of first match; -1 if no match
48     int search(string txt) {
49         int M = sz(pat);
50         int N = sz(txt);
51         int skip;
52         for (int i = 0; i <= N - M; i += skip) {
53             skip = 0;
54             for (int j = M-1; j >= 0; j--) {
55                 if (pat[j] != txt[i+j]) {
56                     skip = max(1, j - right[txt[i+j]]);
57                     break;
58                 }
59             }
60             if (skip == 0) return i;    // found
61         }
62         return -1;                       // not found
63     }
64 
65 };
66 
67 
68 int main() {
69     string txt, pat;
70     cin >> txt;
71     cin >> pat;
72     
73     BoyerMoore *obj = new BoyerMoore(pat);
74     int pos = obj->search(txt);
75     
76     cout << pos << endl;
77     
78     
79     delete obj;
80     return 0;
81 }

BoyerMoore字符串搜索算法

标签:

原文地址:http://www.cnblogs.com/beeshu/p/4231754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!