博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Implement strStr() 解题报告
阅读量:6993 次
发布时间:2019-06-27

本文共 2054 字,大约阅读时间需要 6 分钟。

Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or 
null if needle is not part of haystack.
[解题思路]
时间复杂度线性的解法明显是KMP算法,但是早忘了具体实现了。简单写一个普通的解法。
Update: add a KMP implementation in the end.
[Code]
1:    char *strStr(char *haystack, char *needle) {  2:      // Start typing your C/C++ solution below  3:      // DO NOT write int main() function  4:      if(haystack == NULL || needle == NULL)  5:        return NULL;  6:      int hLen = strlen(haystack);  7:      int nLen = strlen(needle);  8:      if(hLen
[注意]
1. Line 10, 循环的结束应该是hLen-nLen+1,减少不必要运算。
2. Line18, 好久没写指针操作,忘了递增p指针。
增加一个KMP实现, 算法请参考算法导论第32章。
1:    char *strStr(char *haystack, char *needle) {  2:      // Start typing your C/C++ solution below  3:      // DO NOT write int main() function  4:      if(haystack == NULL || needle == NULL) return NULL;  5:         int hlen = strlen(haystack);  6:      int nlen = strlen(needle);  7:      if(nlen ==0) return haystack;  8:      if(hlen == 0 ) return NULL;  9:      int pattern[100000];  10:      GeneratePattern(needle, nlen, pattern);  11:      return Match(haystack, needle, pattern);  12:    }  13:    void GeneratePattern(char* str, int len, int* pattern)  14:    {  15:      pattern[0] = -1;  16:      int k =-1;  17:      for(int j =1; j< len; j++)  18:      {  19:        while(k >-1 && str[k+1] != str[j])  20:          k = pattern[k];  21:        if(str[k+1] == str[j])  22:          k++;  23:        pattern[j] = k;  24:      }  25:    }  26:    char* Match(char* haystack, char* needle, int* pattern)  27:    {  28:      int hlen = strlen(haystack);  29:      int nlen = strlen(needle);      30:      int k =-1;  31:      for(int j =0; j< hlen; j++, haystack++)  32:      {  33:        while(k >-1 && needle[k+1] != *haystack)  34:          k = pattern[k];  35:        if(needle[k+1] == *haystack)  36:          k++;  37:        if(k == nlen-1)  38:          return haystack-k;  39:      }  40:            return NULL;  41:    }

转载于:https://www.cnblogs.com/codingtmd/archive/2012/12/23/5079004.html

你可能感兴趣的文章
虚拟桌面的备份恢复最佳实践 第一部分
查看>>
视频营销,带来SKYCC组合营销软件火爆热销?
查看>>
SuperMap IS.NET不出图的常见问题
查看>>
闲聊Redis
查看>>
flex 学习总结
查看>>
Windows Phone 7 ManipulationStarted 事件
查看>>
解决ubuntu下软件包没有完整安装导致新立得无法打开
查看>>
配置GDB以支持查看stl容器数据
查看>>
Sql Server2005 Transact-SQL 新兵器学习总结之-TRY…CATCH
查看>>
WPF中MVVM模式原理分析与实践(转)
查看>>
javascript控制不同行不同颜色
查看>>
软件工程 软件的估计为什么这么难
查看>>
“如何有效沟通”培训小结
查看>>
[原创].串行ADC TLC549读取实验,Verilog版本
查看>>
用接口管理对象的生命周期.
查看>>
ASPNET_WP.exe进程
查看>>
如何在SSIS的脚本组件中访问变量
查看>>
C#利用Web Service实现短信发送
查看>>
VB中控制AutoCAD退出程序
查看>>
linux 启动过程以及 /etc/rc.d/init.d/目录的一点理解
查看>>