(28)Implement strStr()
题目:返回字符串里子字符串的位置,如果没有则返回-1。
例子:
haystack="abcd",needle="cd",返回2。
haystack="abcd",needle="e",返回-1。
根据这道题我的想法就是搜一遍,当然在第一次搜索的时候,产生一次TLE,原因就是循环中次数的限制没有做对,由于在第一个字符串中找子字符串,所以如果此时搜索的位置后面的长度小于第二个字符串的长度,那么就可以停止了,这样会在两个极长的字符串的查找中减少大量时间。
下面是代码:
class Solution {
public:
int strStr(string haystack, string needle) {
int i,j,temp;
int len1 = haystack.size(), len2 = needle.size();
if(len2 == 0){
return 0;
}
if(len2 > len1){
return -1;
}
for(i = 0; i < len1 - len2 + 1; i ++){
temp = i;
for(j = 0; j < len2; j ++, temp ++){
if(haystack[temp] == needle[j]){
continue;
}
else{
break;
}
}
if(j == len2){
return i;
}
}
return -1;
}
};