Description
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
Brute Force | 一步步来
要把情况考虑周全可不是个简单事~但是可喜可贺,第一次答案比98.94%快:)继续加油!
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "") {
//empty string
return 0;
}
if (needle.size() > haystack.size()) {
return -1;
}
bool isSame = false;
int j = 0;
int set = -1;
for (int i = 0; i < haystack.size(); i++) {
if (haystack[i] == needle[j] && !isSame) {
//first time the same
set = i;
// cout <<"set: "<< set<<endl;
j++;
isSame = true;
} else if (isSame && haystack[i] == needle[j]) {
//continuation of the same thing
j++;
} else if (isSame && haystack[i] != needle[j]) {
//previously the same, but not now
i -= j;
j = 0;
isSame = false;
}
if (j >= needle.size()) {
return set;
}
if (haystack.size() - i <= needle.size() - j) {
return -1;
}
}
return set;
}
};