LeetCode 028 Implement strStr()

题目要求: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)