LeetCode--implement-strstr
2018-01-18 15:19
351 查看
题目描述
Implement strStr().Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
分析:直接暴力求解,时间复杂度为O(mn)
class Solution {
public:
char *strStr(char *haystack, char *needle)
{
int m = strlen(haystack),n = strlen(needle);
if(m<n) return nullptr;
int diff = m-n+1;
for(int start=0;start<diff;start++)
{
int j=0;
for(;j<n;j++)
{
if(haystack[start+j] != needle[j])
break;
}
if(j==n)
{
return haystack+start;
}
}
return nullptr;
}
};
这道题也可以用KMP算法,将复杂度降低为O(m+n)
具体实现就不在展开了,具体可以参考:
http://blog.csdn.net/qq_26437925/article/details/52135791
http://blog.csdn.net/hcbbt/article/details/44099749
讲解kmp算法的可以参考:
https://www.cnblogs.com/yjiyjige/p/3263858.html
http://blog.csdn.net/v_july_v/article/details/7041827
相关文章推荐
- LeetCode-28 Implement strStr() (找出字串位置)
- leetcode_c++:Implement strStr() (028)
- LeetCode 28 Implement strStr() 找到字串返回位置。
- LeetCode: Implement strStr()
- [leetcode]Implement strStr()
- (LeetCode)Implement strStr() --- 匹配字符串
- Implement strStr() -- leetcode
- leetcode-28-Implement strStr()
- [LeetCode] Implement strStr()
- leetcode Implement strStr()
- LeetCode:Implement strStr()
- leetcode--Implement strStr()
- [LeetCode]Implement strStr() 字符串匹配
- [leetcode 28] Implement strStr()
- [LeetCode] Implement strStr() 解题报告
- LeetCode Implement strStr()
- leetcode 日经贴,Cpp code -Implement strStr()
- LeetCode(28)--Implement strStr()
- Leetcode-28: Implement strStr()
- LeetCode : Implement strStr()