首页 > 其他 > 详细

28. 实现 strStr()

时间:2020-03-15 19:58:11      阅读:54      评论:0      收藏:0      [点我收藏+]
 1 //KMP算法
 2 class Solution 
 3 {
 4 public:
 5     //求next数组
 6     vector<int> pre(string& str2)
 7     {
 8         if(str2.size() == 1) return {-1};
 9         vector<int> next(str2.size());
10         next[0] = -1;
11         next[1] = 0;
12         int i = 2;
13         int cn = 0;//cn属于可以跳到的位置
14         while(i < str2.size())
15         {
16             if(str2[i - 1] == str2[cn]) next[i++] = ++cn;
17             else
18             {
19                 if(cn > 0) cn = next[cn];
20                 else next[i++] = 0;
21             }
22         }
23         return next;
24     }
25 
26     //str1长串、str2模式串
27     int strStr(string str1, string str2) 
28     {
29         if(str1.size() < str2.size()) return -1;
30         if(str2.empty()) return 0;
31         int i1 = 0;
32         int i2 = 0;
33         vector<int> next = pre(str2);
34 
35         while(i1 < str1.size() && i2 < str2.size())
36         {
37             if(str1[i1] == str2[i2])
38             {
39                 i1++,i2++;
40             }
41             else if(next[i2] == -1) i1++;
42             else i2 = next[i2];
43         }
44         return i2 == str2.size() ? i1 - i2 : -1;
45     }
46 };

 

28. 实现 strStr()

原文:https://www.cnblogs.com/yuhong1103/p/12499255.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!