Implement strStr ().
Return the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.
Example 1:
Input:haystack = "Hello", needle = "ll" Output:2
Example 2:
Input:haystack = "AAAAA", needle = "BBA" Output: 1
Clarification:
What's should we return when was an needle
empty string? This was a great question to ask during a interview.
For the purpose of this problem, we'll return 0 when was an needle
empty string. This is consistent to C ' s strstr () and Java's IndexOf ().
AC Code:
This code is a low effective.
Class Solution {public: int strStr (String haystack, string needle) { int len1 = Haystack.length (); int len2 = Needle.length (); if (Len2 = = 0) { return 0; } for (int i = 0; i < len1; ++i) { int index = i; int j = 0; while (haystack[index] = = Needle[j] && Index < len1 && J < len2) { index++; j + +; } if (j = = Len2) { return i; } } return-1; }};
Runtime: 812 MS, faster than 3.41% of C + + online submissions for Implement strStr ().
Only there is a little change, but the effective has a big exaltation.
Class Solution {public: int strStr (String haystack, string needle) { int len1 = Haystack.length (); int len2 = Needle.length (); if (Len2 = = 0) { return 0; }
I < len1-len2 for (int i = 0; i < len1-len2+1; ++i) { int index = i; int j = 0; while (haystack[index] = = Needle[j] && Index < len1 && J < len2) { index++; j + +; } if (j = = Len2) { return i; } } return-1; }};
Runtime: 8 ms, faster than 37.69% of C + + online submissions for Implement strStr ().
It is a brute-force algorithm, too. May is this question want the use Brute-force.
The high effective algorithm are to use KMP algorithm.
Class Solution {Public:int strStr (String haystack, string needle) {int m = haystack.length (), n = needle.lengt H (); if (!n) {return 0; } vector<int> lps = kmpprocess (needle); for (int i = 0, j = 0; i < m;) {if (haystack[i] = = Needle[j]) {i++; j + +; } if (j = = N) {return i-j; if ((I < m) && (haystack[i]! = Needle[j])) {if (j) {j = Lps[j -1]; } else {i++; }}} return-1; }private:vector<int> kmpprocess (string& needle) {int n = needle.length (); Vector<int> LPs (n, 0); for (int i = 1, len = 0; i < n;) {if (needle[i] = = Needle[len]) {lps[i++] = ++len; } else if (len) {len = lps[len-1]; } else {lps[i++] = 0; }} return LPs; }};
Runtime: 8 ms, faster than 37.69% of C + + online submissions for Implement strStr ().
Implement StrStr ()