Implement strStr()
Given a haystack string and a needle string, find the first place (starting from 0) where the needle string appears in the haystack string. If not, returns - 1.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
Explain:
When need is an empty string, what value should we return? This is a good question in an interview.
For this problem, we should return 0 when need is an empty string. This matches the C language's strstr() and Java's indexOf() definitions.
Solution 1: use built-in functions
class Solution { public: int strStr(string haystack, string needle) { if(needle.empty()) return 0; int pos=haystack.find(needle);//Find needle in the string haystack if(pos==-1) return -1;//find() not found returned - 1 return pos; } };
Solution 2: use KMP algorithm
class Solution { public: vector<int> next(string str) { vector<int> v; v.push_back(-1);//Insert an element at the end of the vector. int i = 0, j = -1; while (i < str.size()) { if (j == -1 || str[i] == str[j]) { ++i; ++j; v.push_back(j); } else j = v[j]; } return v; } int strStr(string haystack, string needle) { int i = 0;//Main string location int j = 0;//Mode string position int len1 = haystack.size(), len2 = needle.size(); vector<int> nextptr if(needle.empty()) return 0; nextptr = next(needle); while((i < len1)&&(j < len2)) { if((j == -1) || (haystack[i] == needle[j])) //When j=-1, move the position of the main string, and skip the equivalent characters { i++; j++; } else { j = nextptr[j];//Get next matching location } } if (j == needle.size()) return i - j; else return -1; } };