C++ brute-force solution.

  • 4
    int strStr(string haystack, string needle) {
        for (int i = 0; i < (int)(haystack.size()-needle.size()+1); i++) {
            int j = 0;
            while (j < needle.size() && haystack[i+j] == needle[j])
            if (j == needle.size()) 
                return i;
        return -1;

  • 0

    first of all, it is conciser than my brute force solution. then the (int) for size_t casting is necessary otherwise will be an error. well done.

Log in to reply

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