[leetcode]28. Implement strStr()
Analysis
google是一种信仰 —— [ 想吃炒菠菜! ]
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这个题目很简单,就是看haystack这个字符串中是否包含needle,如果包含就返回needle在haystack中出现的位置,否则返回-1。
但是有一点需要注意,就是needle可能是空字符串,而这里默认所有字符串都包含空字符串,所以如果needle是空字符串,就返回0。
Implement
下面就是代码啦~(ps:不知道为啥,感觉自己代码越来越繁琐。。。可以参加那个最难懂代码大赛了!!)
class Solution {
public:
int strStr(string haystack, string needle) {
int len1 = haystack.length();
int len2 = needle.length();
int index, ans;
int tmp = 0;
if(needle=="") return 0;
for(int i=0; i<len1; i++){
if(haystack[i]==needle[0]){
index = i;
ans = i;
tmp = 0;
for(int j=0; j<len2; j++){
if(needle[j]!=haystack[index++])
break;
else
tmp++;
}
if(tmp == len2)
return ans;
}
}
return -1;
}
};