码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 28. Implement strStr() 实现strStr()函数

时间:2018-03-13 13:59:54      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:enc   出现   dia   bsp   leetcode   文本   kmp算法   com   .com   

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()函数

标签:enc   出现   dia   bsp   leetcode   文本   kmp算法   com   .com   

原文地址:https://www.cnblogs.com/lightwindy/p/8555914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!