Why don't you guys use substr? I promise that my code is the shortest and fastest solution ! !

  • -4
    class Solution {
        int strStr(string haystack, string needle) {
            if(needle.length()>haystack.length()) return -1;
            for(int i=0;i<haystack.length()-needle.length()+1;i++)
                if(haystack.substr(i,needle.length())==needle)  return i;
            return -1;

  • 0

    Guys, share your ideas with my code, thks.

  • -3
    This post is deleted!

  • 0

    return haystack.indexOf(needle);

  • 0

    As someone pointed its nice strategy for programmers to use the rock solid existing code, but I think this won't test your ability to write code in the most optimized manner. I implemented this solution initially in 0(n*n) then my solution failed to get submitted. Then I came up with 0(n). If you practice writing optimized code for interview then most likely you will write optimized code at work place.

Log in to reply

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