[LeetCode] 28. Implement strStr() 實現strStr()函數
阿新 • • 發佈:2018-03-13
循環 att bsp pattern tac c++ etc lee pytho
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; } };
[LeetCode] 28. Implement strStr() 實現strStr()函數