leetcode 28. Implement strStr()

Implement strStr().

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

 

实现判断一个字符串是否是一个字符串的子串。如果是,返回该子串第一次出现的位置,如果不是返回-1;

这道题一下子让我想到KMP算法,于是去学习了一下KMP算法。(详见文章1

但是KMP实现好复杂,尤其是那个部分匹配表,所以,还是自己想了。

后来就想到这个方法。

 

组成每个小子串,然后盘点是否匹配。

class Solution {
public:
    bool isSame(string s,string t){
        if(s==t) return true;
        else return false;
    }
    int strStr(string haystack, string needle) {
        int len1=haystack.length();
        int len2=needle.length();
        string tmp="";
        if(len2>len1) return -1;
        if(len2==len1) {
            if(isSame(haystack,needle)) return 0;
            else return -1;
        }
        for(int i=0;i<=len1-len2;i++){
            tmp="";
            for(int j=i;j<i+len2;j++) tmp+=haystack[j];
            if(isSame(tmp,needle)) return i;
        }
        return -1;
    }
};

 

posted @ 2015-12-24 14:15  0giant  阅读(162)  评论(0编辑  收藏  举报