Leetcode28: Implement strStr()
2016-09-23 21:31
441 查看
28.
Implement strStr()
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
在一个字符串haystack中寻找有没有子字符串needle,要是有的话,返回第一次出现的位置,否则返回1。
解法①:
遍历求解。从haystack的第一个元素开始尝试着和needle匹配,将二者的字符进行比较,如果相同,更新答案的index起点值,如果不同,则从index+1开始重新匹配。
代码:[cpp] view
plain
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.size();
int len2=needle.size();
if(len2==0) return 0;
if(len2>len1) return -1;
int cur=0,index=-1,i=0;
bool haveMatch=false;
while(i<len1){
if(needle[cur]==haystack[i]){
if(cur==0){
index=i;
haveMatch=true;
}
cur++;
i++;
if(cur==len2) return index;
}
else if(haveMatch==true){
i=index+1;
cur=0;
haveMatch=false;
}
else{
i++;
}
}
return -1;
}
};
复杂度:
设haystack长度为n,needle长度为m,那么该种解法的时间复杂度是O(nm)。
解法②:
这一题可以利用数据结构中学习过的KMP算法进行求解。利用KMP算法求解该问题的话,时间复杂度为O(n+m)。
Implement strStr()
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
在一个字符串haystack中寻找有没有子字符串needle,要是有的话,返回第一次出现的位置,否则返回1。
解法①:
遍历求解。从haystack的第一个元素开始尝试着和needle匹配,将二者的字符进行比较,如果相同,更新答案的index起点值,如果不同,则从index+1开始重新匹配。
代码:[cpp] view
plain
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.size();
int len2=needle.size();
if(len2==0) return 0;
if(len2>len1) return -1;
int cur=0,index=-1,i=0;
bool haveMatch=false;
while(i<len1){
if(needle[cur]==haystack[i]){
if(cur==0){
index=i;
haveMatch=true;
}
cur++;
i++;
if(cur==len2) return index;
}
else if(haveMatch==true){
i=index+1;
cur=0;
haveMatch=false;
}
else{
i++;
}
}
return -1;
}
};
复杂度:
设haystack长度为n,needle长度为m,那么该种解法的时间复杂度是O(nm)。
解法②:
这一题可以利用数据结构中学习过的KMP算法进行求解。利用KMP算法求解该问题的话,时间复杂度为O(n+m)。
相关文章推荐
- LeetCode(28)题解:Implement strStr()
- LeetCode 28 Implement strStr()(子字符串查找)
- leetcode 28 -- Implement strStr()
- [LeetCode]28 Implement strStr()
- LeetCode-28-Implement strStr()(Sting/穷举)-Easy
- leetcode 28 Implement strStr()
- LeetCode 28 Implement strStr()(实现strStr()函数)
- LeetCode 28_Implement strStr()
- LeetCode 28 Implement strStr()
- LeetCode_OJ【28】Implement strStr()
- LeetCode 28 : Implement strStr() (Java)
- [LeetCode] 28 - Implement strStr()
- LeetCode 28 . Implement strStr()
- leetcode_28题——Implement strStr()(采用KMP算法,还没AC,但自己这边测试无误)
- 【leetcode c++】28 Implement strStr()
- LeetCode-28-Implement strStr() KMP模板题
- leetcode[28]:Implement strStr()
- 【LeetCode】28 - Implement strStr()
- leetcode_171 Excel Sheet Column Number & leetcode_28 Implement strStr()
- LeetCode 28 Implement strStr()