首页 > 代码库 > [Leetcode] implement strStr() (C++)

[Leetcode] implement strStr() (C++)

题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

Tag:

String; Two Pointers

体会:

这道题是字符串的匹配问题,目前还只会朴素的逐步方法,但是这道题还有KMP解法,和Boyer-Moore的解法,目前还没有掌握。

先把笔记放到这里,以后再来解决吧。

1. KMP算法

2. Boyer-Moore算法

 1 class Solution { 2 public: 3     int strStr(char *haystack, char *needle) { 4         int i = 0; 5         int j = 0; 6         while (haystack[i] && needle[j] ) { 7             if (haystack[i] == needle[j]) { 8                 i++; 9                 j++;10             } else {11                 i = i - j + 1;12                 j = 0;13             }14         }15         return (needle[j] ? -1 : i - j);16     }17 };

 

 

[Leetcode] implement strStr() (C++)