您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: