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



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

題目:


解答:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int i = 0;
        int h_size = haystack.size();
        int n_size = needle.size();

        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[0], n_size)) {
                return i;
            }
        }
        return -1;
    }
};