28.实现strStr()
题目链接
复习了下kmp
class Solution {
public:
typedef vector<int> vi;
vi nxt;
void getnext(string needle){
int len=needle.length();
nxt=vi(len+10);nxt[0]=-1;
int i=0,j=-1;
while(i<len){
if(j==-1||needle[i]==needle[j])nxt[++i]=++j;
else j=nxt[j];
}
}
int strStr(string haystack, string needle) {
if(needle.empty())return 0;
getnext(needle);
int la=haystack.length(),lb=needle.length();
int i=0,j=0;
while(i<la&&j<lb){
if(j==-1||haystack[i]==needle[j]){i++,j++;}
else j=nxt[j];
}
if(j==lb)return i-lb;
return -1;
}
};
如果偷懒的话可以
class Solution {
public:
int strStr(string haystack, string needle) {
//if(needle.empty())return 0;//加上这一行会快4ms(8->4)
return haystack.find(needle);
}
};
35.搜索插入位置
题目链接
二分不想写偷懒了,不过这里可以复习一下lower_bound和upper_bound
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
return lower_bound(nums.begin(),nums.end(),target)-nums.begin();
}
};