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(from0tohaystack.length() - needle.length()) and see if the following characters inhaystackmatch those ofneedle。
KMP
python
Last updated
Was this helpful?