#Question
Implement strStr()
.Return the index of the first occurrence of needle in haystack, or -1
if needle
is not part of haystack
.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
Example1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
Example3:
Input: haystack = “”, needle = “”
Output: 0
Answer
##思路一:
两个字符长度相减+1得到的长度就是需要比较的长度,当needle长度为0时,返回0。当haystack与needle不匹配时,返回-1。当haystack与needle匹配时,返回i的值。时间复杂度为O($n^{2}$),空间复杂度为O(n),具体代码如下:
1 | class Solution { |
##思路二:
KMP(字符串查找算法),lps是needle的索引。这里使用的kmp算法,把needle作为kmp前缀,来进行字符比对。如果字符相同,那么len增加。如果不相等,就要看len的值,如果len的值为0那么就将lps[i]的值设置为0。如果len不为零,那么就把lps[len-1]的值赋给len,这一步是为了防止对应字符中间出现了不相等的,将字符串右移。时间复杂度为O(n);
1 | class Solution { |