题目:
在一个字符串中寻找另外一个字符,如果有返回首次出现的索引,否则返回-1
思路:
1.使用双指针方法
2.当不满足的时候进行清空(j=0)并回指(i=i-j)
3.当寻找字符为空时返回0
时间复杂度:
最坏时间复杂度为 O((N - L)L),最优时间复杂度为 O(N)
代码:(手写find)
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.length()==0)
return 0;
int j=0;
for(int i=0;i<haystack.length();i++)
if(haystack[i]==needle[j]){
j++;
if(j==needle.length())
return i-needle.length()+1;
}
else{
i=i-j;
j=0;
}
return -1;
}
};
代码:(调用find)
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};
收获:
1.学会利用双指针解决字符串匹配问题
2.明白字符串find的内部原理
以前都是用find(‘***’)=-1比较多,现在知道对于寻找空字符是返回0,其他情况返回查找到的首位索引。