0. 题目
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 whenneedle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 whenneedle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
1. C++版本
注意,当haystack字符串更短的时候,不要交换haystack和needle,多次一举。
"mississippi" "issip"
这种特例
if (needle.empty())
return 0;
int i = 0, j = 0, firstIndex = -1, flag=0;
for (;i<haystack.size() && j<needle.size(); ) {
if (needle[j] == haystack[i]) {
if (flag == 0) {
firstIndex = i;
flag = 1;
}
i++;j++;
}
else {
if (firstIndex != -1) {
i = firstIndex;
j = 0;
}
i++;
firstIndex = -1;
flag = 0;
}
}
if (j != needle.size())
return -1;
return firstIndex;
}
2. python版本
TODO
网友评论