LeetCode 28 - Implement strStr()

一、问题描述

Description:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

实现函数strStr(string haystack, string needle),用于字符串匹配。

  • 若字符串匹配成功,返回 needle 在 haystack 中第一次出现的位置。
  • 若字符串匹配不成功,返回-1。


二、解题报告

解法一:朴素的字符串匹配

朴素的字符串匹配算法就是:枚举 0snm 的所有起点,检查是否满足条件P[1...m] = T[s+1...s+m]

代码很简洁:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = needle.size();
        int n = haystack.size();
        int index = -1;
        for(int i=0; i<=n-m; ++i) {
            if(needle.compare(haystack.substr(i, m)) == 0) {
                index = i;
                break;
            }
        }
        return index;
    }
};

AC 时间 4ms 。


解法二:KMP算法

class Solution {
public:
    int* prefixFunction(string pattern)
    {
        int len = pattern.size();
        int k = 0;

        int *pi = new int[len];
        for(int i=0; i<len; i++)     // 初始化为0
            pi[i] = 0;

        for(int i=1; i<len; i++)
        {
            while (k>0 && pattern[k]!=pattern[i])
                k = pi[k-1];

            if (pattern[k]==pattern[i])
                k = k+1;

            pi[i] = k;
        }

        return pi;
    }

    int strStr(string haystack, string needle)
    {
        if(needle == "")
            return 0;

        int n = haystack.size();
        int m = needle.size();
        int *pi = prefixFunction(needle);

        int q=0;
        for(int i=0; i<n; i++)
        {
            while (q>0 && needle[q]!=haystack[i])
                q = pi[q-1];

            if (needle[q]==haystack[i])
                q = q+1;

            if ( q == m )
                return i - m + 1;
        }
        return -1;
    }
};

AC 时间 4ms 。





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


posted @ 2015-05-24 23:32  神奕  阅读(131)  评论(0编辑  收藏  举报