C++ O(NM) solution


  • 0
    G

    Native solution where we are trying to find needle from each position in haystack.

    int strStr(string haystack, string needle) {
        if (haystack.empty() && needle.empty())
            return 0;
        for (int base = 0; base < haystack.size(); base++) {
            int i = base;
            for (; i - base < needle.size() && i < haystack.size(); i++)
                if (haystack[i] != needle[i - base])
                    break;
            if (i - base == needle.size())
                return b;
        }
        return -1;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.