LeetCode 028 Implement strStr()

3332 ワード

タイトル要求: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;

    }

};