题目

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Update (2014-11-02):

The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.

分析

这是一道模式匹配算法。给定两个字符串haystack与needle,给出needle在haystack全然匹配的首位置坐标(从0開始)。

这道题在数据结构中有解说,除了開始的简单模式匹配算法BF算法,还给出了改进后的KMP经典算法。以下分别用这两个算法实现。

AC代码

class Solution {
public:
//简单模式匹配算法(BF算法)
int strStr(string haystack, string needle) {
int len = strlen(haystack.c_str()), nl = strlen(needle.c_str()); int i = 0, j = 0;
while (i < len && j < nl)
{
if (haystack[i] == needle[j])
{
i++;
j++;
}
else{
i = i - j + 1;
j = 0;
}//else
}//while if (j == nl)
return i - nl;
else
return -1;
}
};

KMP算法实现

class Solution {
public:
//简单模式匹配算法(BF算法)
int strStr(string haystack, string needle) {
int len = strlen(haystack.c_str()), nl = strlen(needle.c_str()); int i = 0, j = 0;
while (i < len && j < nl)
{
if (haystack[i] == needle[j])
{
i++;
j++;
}
else{
i = i - j + 1;
j = 0;
}//else
}//while if (j == nl)
return i - nl;
else
return -1;
} //从字符串haystack的第pos个位置開始匹配
int KMP(const string &haystack, const string &needle, int pos)
{
int len = strlen(haystack.c_str()), nl = strlen(needle.c_str()); int i = pos, j = 0;
int *n = Next(needle);
while (i < len && j < nl)
{
if (j == -1 || haystack[i] == needle[j])
{
i++;
j++;
}
else{
j = n[j];
}//else
}//while if (j == nl)
return i - nl;
else
return -1; } int* Next(const string &s)
{
int i = 0, j = -1;
int next[500] ;
int len = strlen(s.c_str());
next[0] = -1;;
while (i < len)
{
while (j >-1 && s[i] != s[j])
j = next[j];
i++;
j++; if (s[i] == s[j])
next[i] = next[j];
else
next[i] = j;
}//while
return next;
}
};

GitHub測试程序源代码

最新文章

  1. 跟我学Angular2(1-初体验)
  2. MFC之TreeCtrl控件使用经验总结
  3. 如何删除GIT中的.DS_Store
  4. Android ANR分析(三)
  5. select 练习4
  6. PHPCMS V9静态化HTML生成设置及URL规则优化
  7. 前端面试库_JS部分_02
  8. makefile 学习(一)
  9. 读FCL源码系列之List&lt;T&gt;---让你知其所以然---内含疑问求大神指点
  10. RSS实例文档
  11. 【转载】nginx 并发数问题思考:worker_connections,worker_processes与 max clients
  12. 解决ie6里png图片透明变白色bug
  13. SqlServer创建数据表描述及列描述信息
  14. 在Windows环境下设置terminal下调试adb
  15. 全排列Permutations
  16. dotnet core 自定义配置文件
  17. [bzoj1731] [Usaco2005 dec]Layout 排队布局
  18. jsonViewer json格式化工具
  19. K3数据字典备查
  20. odoo 配置文件

热门文章

  1. mysql 四 表操作
  2. Linux终端彩色打印+终端进度条【转】
  3. vi错误terminal too wide解决方法
  4. select实现斐波那契和超时机制
  5. MYSQL通过索引优化数据库的查询
  6. SVN代码提交
  7. Appium+python自动化28-name定位【转载】
  8. python3的leetcode题,两个数求和等于目标值,返回这两个数的索引组成的列表(三种方法)
  9. python 多进程并发与多线程并发
  10. spring quartz job autowired 出错 null pointer