Fork me on GitHub

【LeetCode】28. Implement strStr()

题目:

Implement strStr().

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

提示:

此题可以使用暴力搜索方法。当然也可以使用其他一些高级方法,如:Rabin-Karp, KMP等等。这些算法打算等之后对他们更了解了以后,单独写一些文章对其总结。因此这里仅给出暴力搜索方法。

代码:

class Solution {
public:
    int strStr(string haystack, string needle) {
      int hay_len = haystack.size();
      int needle_len = needle.size();
      if (needle_len == 0) return 0;
      if (hay_len == 0) return -1; 
      int i = 0, j = 0, p;
      for (i = 0; i <= hay_len - needle_len; ++i) {
          for (p = i, j = 0; j < needle_len; ++j, ++p) {
              if (haystack[p] != needle[j]) break;
          }
          if (j == needle_len) return i;
      }
      return -1;
  }
};
posted @ 2015-08-28 10:32  __Neo  阅读(193)  评论(0编辑  收藏  举报