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
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().
LeetCode:链接
这题就是最长公共字符串匹配。
第一种方法:暴力匹配法
即从haystack开始第一个字符与needle第一个字符匹配,如果匹配,则i++,j++,继续往下走,否则中间一旦发生不匹配,则haystack则从第二个字符开始于needle第一个字符重新开始匹配。重复这个过程,如果中间j走到needle结尾,则匹配成功,如果i走到了haystack结尾处,而j还没有,则匹配失败。
必须得有needle长度那么大才可以判断,不能for i in range(n),会超时。
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
n = len(haystack)
m = len(needle)
'''必须得有needle长度那么大才可以判断 不能for i in range(n) 会超时'''
for i in range(n-m+1):
j = 0
'''在needle范围内判断'''
while j < m:
'''只要有不相等 直接退出循环'''
if haystack[i+j] != needle[j]:
break
j += 1
'''如果此时的j和needle的长度相等 说明匹配到了'''
if j == m:
return i
return -1
第二种方法:KMP。
class Solution(object):
def get_partital_table(self, needle):
m = len(needle)
partital_table = [0] * m
i, j = 1, 0
while i < m:
if needle[i] == needle[j]:
partital_table[i] = j + 1
i += 1
j += 1
else:
if j > 0:
j = partital_table[j-1]
else:
partital_table[i] = 0
i += 1
return partital_table
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
n, m = len(haystack), len(needle)
partital_table = self.get_partital_table(needle)
i, j = 0, 0
while i < n:
if haystack[i] == needle[j]:
i += 1
j += 1
else:
if j > 0:
j = partital_table[j-1]
else:
i += 1
if j == m:
return i - m
return -1