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

LeetCode 028 Implement strStr()

时间:2015-02-07 17:13:25      阅读:117      评论: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.

 

代码如下:

class Solution {
public:
    int strStr(char *haystack, char *needle) {
        // if needle is empty return the full string
        //if (!*needle) return (char*) haystack;
        if (needle[0] == \0) return 0;
        
        int p1, p2, p1_advance = 0;
        
        for(p2 = 1; needle[p2]; p2++){
            p1_advance++;   //提前算好needle长度
        }
        
        //如果haystack[p1_advance]为空,则不必比较了!
        //长度都不够!
        for(p1 = 0; haystack[p1_advance]; p1_advance++){
            int p1_old = p1;
            p2 = 0;
            //都不为空,且相等,则一直比较
            while(haystack[p1] && needle[p2] && haystack[p1] == needle[p2]){
                p1++;
                p2++;
            }
            //如果比较到了needle结尾,则成功
            if(needle[p2] == \0) 
                return p1_old;
            p1 = p1_old + 1;
        }
        return -1;
    }
};

 

LeetCode 028 Implement strStr()

标签:

原文地址:http://www.cnblogs.com/510602159-Yano/p/4279013.html

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