6ms cpp solution in 6 lines without handling edge cases separately


  • 0
        int strStr(string haystack, string needle) {
            int pos = 0;
            while (true) {
                if (pos + needle.length() > haystack.length() + 1) return -1;
                if (haystack.substr(pos, needle.length()) == needle) return pos;
                while (pos++ < haystack.length() && haystack[pos] != needle[0]);
            }
        }

Log in to reply
 

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