题目链接:
题目:
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().
题目分析:
实现 strStr().的功能,即找到一个字符串在另一个字符串中的位置,如果有返回开始下标,如果没有返回 -1。
解题思路:
简单模拟题,利用两个指针 s 和 e ,s指向haystack,e指向needle。e始终都是从0开始,而s 则是遍历haystack。
当出现两者指向的字符相等时,就继续往后,一直判断到,e指向的needle最后一个也想等,那就返回一开始 s 的值。
如果中途出现不相等的,那就将 s 变回原来的值,接着下去遍历haystack,同时将e 重复赋为 0。
为了减少运行时间,我们可以考虑在满足某些情况下,就马上返回值,减少运行时间。
一开始,如果needle 长度为0,那就直接返回值为0。
如果needle长度大于haystack长度,不可能找到,那就返回 -1。
同时这个条件在 s 遍历haystack情况下也满足,当遍历s ,导致剩下的 haystack长度 - s,小于needle长度时,也说明不可能找到,那就返回 -1。
AC代码:
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size()==0)
return 0;
if(needle.size() > haystack.size())
return -1;
int s = 0,e = 0;
for(int i = 0;i < haystack.size();i++){
e = 0;
if(haystack.size()-i < needle.size())
return -1;
if(haystack[i] == needle[e]){
s = i;
while(haystack[s] == needle[e] && e<needle.size() && s<haystack.size()){
s++;e++;
}
if(e == needle.size())
return i;
}
}
return -1;
}
};