A clean c++ AC solution, brute force, no strlen needed.

  • 2
    class Solution {
        int strStr(char *haystack, char *needle) {
            int i = 0;
            while (true) {
                char *p1 = haystack;
                char *p2 = needle;
                for (; *p1 == *p2 && *p1 != 0 && *p2 != 0; p1++, p2++) {}
                if (*p2 == 0) return i;
                if (*p1 == 0) return -1;
            return -1;

    If the end of haystack is met first, the loop (and the function) can be safely terminated by returning -1, to avoid TLE for long needle. If the end of needle is met first, it is a success matching. It is the same brute-force algorithm but no need to get any strlen at first.

Log in to reply

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