您的位置:首页 > 其它

Leetcode28: Implement strStr()

2016-09-23 21:31 441 查看
28.
Implement strStr()

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

题意:

在一个字符串haystack中寻找有没有子字符串needle,要是有的话,返回第一次出现的位置,否则返回1。

解法①:

遍历求解。从haystack的第一个元素开始尝试着和needle匹配,将二者的字符进行比较,如果相同,更新答案的index起点值,如果不同,则从index+1开始重新匹配。

代码:[cpp] view
plain

class Solution {  

public:  

    int strStr(string haystack, string needle) {  

        int len1=haystack.size();  

        int len2=needle.size();  

        if(len2==0) return 0;  

        if(len2>len1) return -1;  

        int cur=0,index=-1,i=0;  

        bool haveMatch=false;  

        while(i<len1){  

            if(needle[cur]==haystack[i]){  

                if(cur==0){  

                    index=i;  

                    haveMatch=true;  

                }  

                cur++;  

                i++;  

                if(cur==len2) return index;  

            }  

            else if(haveMatch==true){  

                i=index+1;  

                cur=0;  

                haveMatch=false;  

            }  

            else{  

                i++;  

            }  

        }  

        return -1;  

    }  

};

复杂度:

设haystack长度为n,needle长度为m,那么该种解法的时间复杂度是O(nm)。

解法②:

这一题可以利用数据结构中学习过的KMP算法进行求解。利用KMP算法求解该问题的话,时间复杂度为O(n+m)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: