28. Implement strStr()

28. Implement strStr()

My Submissions
Question
Total Accepted: 85665  Total Submissions: 360485  Difficulty: Easy

Implement strStr().

题目意思:找到needle字符串在haystack字符串中第一次出现的下标,返回即可。

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

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems

KMP算法

就是KMP算法,没撒子好分析的!
复习算法导论:http://blog.csdn.net/ebowtang/article/details/49129363

class Solution {
public:
    //计算模式needle的部分匹配值,保存在next数组中      
    void MakeNext(const string &P, vector<int> &next) {  
        int q, k;//k记录所有前缀的对称值      
        int m = P.size(); 
        next[0] = 0;//首字符的对称值肯定为0      
        for (q = 1, k = 0; q < m; ++q)//计算每一个位置的对称值      
        {  
            //k总是用来记录上一个前缀的最大对称值      
            while (k > 0 && P[q] != P[k])  
                k = next[k - 1];//k将循环递减,值得注意的是next[k]<k总是成立      
            if (P[q] == P[k])  
                k++;//增加k的唯一方法      
            next[q] = k;      
        }  
    } 
    int strStr(string haystack, string needle) {
        if(needle.empty())
            return 0;
        if(haystack.empty())
            return -1;
        int n = haystack.size();  
        int m = needle.size();  
        vector<int> next(m,0);
        MakeNext(needle, next);  
        for (int i = 0, q = 0; i < n; ++i)  
        {  
            while (q > 0 && needle[q] != haystack[i])  
                q = next[q - 1];  
            if (needle[q] == haystack[i])  
                q++;  
            if (q == m)  
                return (i - m + 1); 
            else if(i==n-1)
                return -1;
        }  
    }
};



别人家的算法:

(BF算法)

class Solution {
public:
    //简单模式匹配算法(BF算法)
    int strStr(string haystack, string needle) {
        int hlen = strlen(haystack.c_str());
        int nlen = strlen(needle.c_str());

        int i = 0, j = 0;
        while (i < hlen && j < nlen)
        {
            if (haystack[i] == needle[j])//相等
            {
                i++;
                j++;
            }
            else{//一旦有不匹配的某两个字符
                i = i - j + 1;//i重新匹配的位置
                j = 0;//相同的字符数量清零
            }
        }

        if (j == nlen)
            return i - j;
        else
            return -1;
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50480410

原作者博客:http://blog.csdn.net/ebowtang

你可能感兴趣的:(LeetCode,面试,字符串处理,kmp算法)