程式語言 - LeetCode - C - 28. Find the Index of the First Occurrence in a String



參考資訊:
https://www.cnblogs.com/grandyang/p/4606696.html

題目:


解答:

int strStr(char *haystack, char *needle)
{
    int i = 0;
    int h_size = strlen(haystack);
    int n_size = strlen(needle);

    if (!h_size || !n_size) {
        return -1;
    }
    
    for (i = 0; i <= (h_size - n_size); i++) {
        if ((haystack[i] == needle[0]) && !memcmp(&haystack[i], needle, n_size)) {
            return i;
        }
    }
    return -1;
}