LeetCode28 Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
思路:首先找到needle有可能出现的起始位置,然后再看从起始位置处开始,后面的needle是否吻合,需要记录的是吻合的字符串的长度,当长度达到needle的长度的时候,立即返回。如果在检查的过程中有一个字母不吻合就可以重新查找初始位置了。值得注意的是,如果needle的长度为0,应该返回0。
用时略多,为了做一些简化,我们可以这样思考,当我们查看haystack中的所有字符时,如果未被查看的长度已经小于needle了,那么剩下的字符串绝对不可能与needle匹配了。
另外一种算法是kmp算法,kmp本身就是一种高效的字符串匹配的方法,虽然在这道题里和上面改进的暴力解速度差不多。