28. Implement strStr() - cocoder39/coco39_LC GitHub Wiki

28. Implement strStr()

time is O(m * n)

haystack: qqqqqqqqqqqqq
needle:   qqqa
int strStr(string haystack, string needle) {
        int m = haystack.length();
        int n = needle.length();
        if (n > m) {
            return -1;
        }
        
        for (int i = 0; i <= m - n; i++) {
            int j = 0;
            for (; j < n; j++) {
                if (haystack[i + j] != needle[j]) {
                    break;
                }
            }
            if (j == n) {
                return i;
            }
        }
        return -1;
    }