[LeetCode] Implement strStr()

代码:

暴力算法

 1 class Solution {

 2 public:

 3     int strStr(char *haystack, char *needle) {

 4         if (!*needle)

 5             return 0;

 6         int alen = strlen(haystack);

 7         int blen = strlen(needle);

 8         int i = 0, j = 0;

 9         while (i < alen && j < blen) {

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

11                 i++;

12                 j++;

13             } else {

14                 i = i - j + 1;

15                 j = 0;

16             }

17         }

18         if (j == blen) {

19             return i - j;

20         } else {

21             return -1;

22         }

23     }

24 };

KMP算法

 1 class Solution {

 2 public:

 3     int strStr(char *haystack, char *needle) {

 4         return kmp(haystack, needle);

 5     }

 6 private:

 7     int kmp(const char *text, const char *pattern) {

 8         int i = 0;

 9         int j = 0;

10         const int n = strlen(text);

11         const int m = strlen(pattern);

12         int *next = (int*)malloc(sizeof(int)* m);

13         compute_prefix(pattern, next);

14 

15         while (i < n && j < m) {

16             if (j == -1 || text[i] == pattern[j]) {

17                 i++;

18                 j++;

19             } else {

20                 j = next[j];

21             }

22         }

23 

24         free(next);

25         if (j == m)

26             return i - j;

27         else

28             return -1;

29     }

30 

31     void compute_prefix(const char *pattern, int next[]) {

32         int i = 0;

33         int j = -1;

34         const int m = strlen(pattern);

35         next[0] = -1;

36 

37         while (i < m - 1) {

38             if (j == -1 || pattern[i] == pattern[j]) {

39                 i++;

40                 j++;

41                 if (pattern[i] != pattern[j])

42                     next[i] = j;

43                 else

44                     next[i] = next[j];

45             }

46             else {

47                 j = next[j];

48             }

49         }

50     }

51 };

 

杂记:

参考:http://blog.csdn.net/v_july_v/article/details/7041827

你可能感兴趣的:(LeetCode)