题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路:
直接暴力掉了。。
public class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null ||
(haystack.length() == 0 && needle.length() != 0)) {
return -1;
}
if ((haystack.length() == 0 && needle.length() == 0) ||
(haystack.length() != 0 && needle.length() == 0)) {
return 0;
}
for (int i = 0;i < haystack.length()-needle.length()+1;i++) {
if (haystack.charAt(i) == needle.charAt(0)) {
int j;
for (j = 1;j < needle.length();j++) {
if (haystack.charAt(i+j) != needle.charAt(j)) {
break;
}
}
if (j == needle.length()) {
return i;
}
}
}
return -1;
}
}
用Rabin-Karp algorithm算法实现(思路完全按算法导论来的,这里就不说了,主要是Python暴力好像AC不了,有一个卡暴力的数据。。):
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle) == 0:
return 0
n = len(haystack)
m = len(needle)
if n < m:
return -1
d = 26
q = 14983
p = 0
t = 0
h = 1
for i in range(0, m - 1):
i += 1
h = (h * (d % q)) % q
for i in range(0, m):
p = (p * d + ord(needle[i]) - ord('a')) % q
t = (t * d + ord(haystack[i]) - ord('a')) % q
for i in range(0, n - m + 1):
if p == t:
return i
if i < n - m:
t = ((t + q - (ord(haystack[i]) - ord('a')) * h) * d + ord(haystack[i + m]) - ord('a')) % q
return -1