首页 > 其他 > 详细

[LeetCode] Implement strStr()

时间:2015-04-24 16:22:13      阅读:92      评论:0      收藏:0      [点我收藏+]

Implement strStr()

Implement strStr().

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

解题思路:

1、暴力法。逐一匹配,然后回溯。代码如下,但是产生超时错误。

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1=haystack.length();
        int len2=needle.length();
        if(len2>len1){
            return -1;
        }
        for(int i=0; i<len1; i++){
            int j=0;
            for(; j<len2&&i+j<len1; j++){
                if(haystack[i+j]!=needle[j]){
                    break;
                }
            }
            if(j==len2){
                return i;
            }
        }
        return -1;
    }
};

2、KMP算法。

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1=haystack.length();
        int len2=needle.length();
        if(len2>len1){
            return -1;
        }
        if(len2==0){
            return 0;
        }
        int next[len2];
        next[0]=-1;
        int i=0, j=-1;
        
        while(i<len2){
            if(j==-1||needle[j]==needle[i]){
                i++;
                j++;
                next[i]=j;
            }else{
                j=next[j];
            }
        }
        
        i=0; j=0;
        while(i<len1){
            if(j==-1||haystack[i]==needle[j]){
                i++;
                j++;
            }else{
                j=next[j];
            }
            if(j==len2){
                return i-len2;
            }
        }
        
        return -1;
    }
};


[LeetCode] Implement strStr()

原文:http://blog.csdn.net/kangrydotnet/article/details/45246869

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!