Implement strStr()

C++

class Solution
{
  public:
    int strStr(string haystack, string needle)
    {
        if (needle.size() == 0)
            return 0;
        string::size_type position = haystack.find(needle);
        if (position != haystack.npos)
        {
            cout << "position is: " << position << endl;
            return position;
        }
        else
        {
            cout << "Not found." << endl;
            return -1;
        }
    }
};

Brute-Force

  • Traverse all the possible starting points of haystack (from 0 to haystack.length() - needle.length() ) and see if the following characters in haystack match those of needle

KMP

python

Last updated

Was this helpful?