码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 28. Implement strStr()

时间:2015-12-24 15:02:15      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

 

leetcode 28. Implement strStr()

标签:

原文地址:http://www.cnblogs.com/LUO77/p/5072909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!