LeetCode:Implement strStr()

来源:互联网 发布:mac压感 编辑:程序博客网 时间:2024/05/23 19:10

一、问题描述

Implement strStr().

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

二、思路

方法一暴力求解,方法二KMP算法

三、代码

方法一:

class Solution {public:    int strStr(string haystack, string needle) {        if(haystack==""&&needle ==""|| needle =="") return 0;        int i,j;        for(i = 0,j = 0; i < haystack.size()&& j < needle.size();){                if(haystack[i] == needle[j]){                    ++i;                    ++j;                }else{                    i = i - (j - 1);                    j = 0;                }        }                        return j != needle.size() ? -1 : i - j;    }};

方法二:

class Solution {public:    int strStr(string haystack, string needle) {        if(needle.empty()) return 0;        int i, j;        // preprocess        vector<int> b(needle.length() + 1, -1);        i = 0;        j = -1;        b[0] = j;        while(i < needle.length()){            while(j != -1 && needle[i] != needle[j]) j = b[j];            ++i, ++j;            b[i] = j;        }                // find        i = 0;        j = 0;        while(i < haystack.length()){            while(j != -1 && haystack[i] != needle[j]) j = b[j];            ++i, ++j;            if(j == needle.length()) return i - j;        }        return -1;    }};


0 0
原创粉丝点击