[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;  // index under examine in haystack

 5         int j = 0;  // index under examine in needle

 6         

 8         while (haystack[i] && needle[j]) {

 9             if (haystack[i] == needle[j]) {

11                 i++;

12                 j++;

13             } else {

14                 // roll back:

15                 // reset haystack index back to (i - j + 1), since in current examine

16                 // start index in haystack is (i - j)

17                 i = i - j + 1;

18                 // reset needle back to its beginning

19                 j = 0;

20             }

21         }

22         // if haystack ends but needle not ends, 

23         // we know needle is not in the haystack, then return -1.

24         return (needle[j]) ? -1 : (i - j);

25     }

26 };

 

 

 

 

你可能感兴趣的:(LeetCode)