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();
}
};

本文深入解析了LeetCode上的两道经典算法题:28. 实现strStr()与35. 搜索插入位置。首先介绍了使用KMP算法解决字符串匹配问题的方法,随后通过二分查找和标准库函数lower_bound演示了如何高效地找到目标值的插入位置。文章提供了详细的代码实现和思路分析。
138

被折叠的 条评论
为什么被折叠?



