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
在一个字符串中找另一个字符串第一次出现的位置。
解法2:从第1个字母开始循环,检查由当前字母s[i]到s[i+len(needle)]是否等于needle。T: O(n * k), S: O(k)
解法2:Knuth-Morris-Pratt字符串查找算法(简称为KMP算法)可在一个主文本字符串S内查找一个词W的出现位置。T: O(n + k), S: O(k)
Python: KPM
class Solution(object): def strStr(self, haystack, needle): if not needle: return 0 return self.KMP(haystack, needle) def KMP(self, text, pattern): prefix = self.getPrefix(pattern) j = -1 for i in xrange(len(text)): while j > -1 and pattern[j + 1] != text[i]: j = prefix[j] if pattern[j + 1] == text[i]: j += 1 if j == len(pattern) - 1: return i - j return -1 def getPrefix(self, pattern): prefix = [-1] * len(pattern) j = -1 for i in xrange(1, len(pattern)): while j > -1 and pattern[j + 1] != pattern[i]: j = prefix[j] if pattern[j + 1] == pattern[i]: j += 1 prefix[i] = j return prefix
Python:
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in xrange(len(haystack) - len(needle) + 1): if haystack[i : i + len(needle)] == needle: return i return -1
C++:
class Solution { public: int strStr(string haystack, string needle) { if (needle.empty()) return 0; int m = haystack.size(), n = needle.size(); if (m < n) return -1; for (int i = 0; i <= m - n; ++i) { int j = 0; for (j = 0; j < n; ++j) { if (haystack[i + j] != needle[j]) break; } if (j == n) return i; } return -1; } };