码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Implement strStr()

时间:2015-03-20 01:13:34      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

Brute Force:

 1 class Solution {
 2 public:
 3     int strStr(char *haystack, char *needle) {
 4         if (!haystack) return -1;
 5         if (!needle) return 0;
 6         int index = 0, tmp1 = 0, tmp2 = 0;
 7         while (haystack[index]) {
 8             if (haystack[index] == needle[0]) {
 9                char *tmp1 = haystack, *tmp2 = needle;
10                while (tmp1 && tmp2 && *tmp1 == *tmp2) {
11                    tmp1++;
12                    tmp2++;
13                }
14                if (!tmp2) return index;
15             }
16             index++;
17         }
18         return -1;
19     }
20 };

 

KMP:

Intialize a dp map for search whether there has duplicate chars in needle.

j = dp[i-1] is starting from the previous step

 1 class Solution {
 2 public:
 3     int strStr(char *haystack, char *needle) {
 4         if (!haystack) return -1;
 5         if (!needle) return 0;
 6         int len = strlen(needle), i = 0, j = 0; 
 7         vector<int> dp(len, -1);
 8         for (int i = 1; i < len; i++) {
 9             for (j = dp[i-1]; j >= 0 && needle[i] != needle[j+1]; j = dp[j]);
10             if (needle[i] == needle[j+1]) dp[i] = j+1;
11         }
12         i = 0, j = 0;
13         while (haystack[i] && needle[j]) {
14             if (haystack[i] == needle[j]) {
15                 i++;
16                 j++;
17             } else if (j == 0) i++;
18             else j = dp[j-1] + 1;
19         }
20         if (needle[j]) return -1;
21         return i-j;
22     }
23 };

 

.

 

LeetCode – Refresh – Implement strStr()

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352274.html

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