Topic_Array——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

题目特点和要求:

  1. needle数组为空的时候,返回0
  2. 需要考虑到时间复杂度

题目思路:
  两个字符串数组,进行匹配的时候首先想到two pointers的思路。

  pointer_haystack 和 pointer_needle 分别指向两个字符串数组。

  当pointer_haystack 和 pointer_stack指向相同的字符时,将进入比对状态,要记录此刻pointer_haystack位置,因为这是下一次比对的开始。并使两个pointer一同向后移动。

  当遇到不同的字符时,要将pointer_stack重置为0,同时将pointer_haystack置于刚才保存的位置+1。

  当pointer_stack已经走到末尾,说明一次匹配已经结束,这时退出循环,并将pointer_haystack保留的字符开始位置返回。


posted on 2019-01-16 23:37  KissMe3Times  阅读(89)  评论(0)    收藏  举报