首页 > 其他 > 详细

Leetcode#28 Implement strStr()

时间:2015-01-26 13:28:59      阅读:275      评论:0      收藏:0      [点我收藏+]

原题地址

 

因为是道简单题,所以最简单的字符串匹配应该也能过,但还是练习一下KMP算法为好。KMP算法的介绍可以参考这篇

以后有时间试试Boyer-Moore算法

代码:

 1 int strStr(char *haystack, char *needle) {
 2   if (!needle[0]) return 0;
 3   int n = strlen(needle);
 4   int *next = new int[n + 1];
 5   int i, j;
 6 
 7   i = 0;
 8   j = -1;
 9   next[0] = -1;
10   while (needle[i]) {
11     if (j < 0 || needle[i] == needle[j]) {
12       i++;
13       j++;
14       next[i] = j;
15     }
16     else
17       j = next[j];
18   }
19 
20   i = 0;
21   j = 0;
22   while (haystack[i] && j < n) {
23     if (j < 0 || haystack[i] == needle[j]) {
24       i++;
25       j++;
26     }
27     else
28       j = next[j];
29   }
30 
31   return j == n ? i - n : -1;
32 }

 

Leetcode#28 Implement strStr()

原文:http://www.cnblogs.com/boring09/p/4249895.html

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