[leetcode] Implement strStr()
2015-08-13 11:22
330 查看
题目链接在此
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
模式匹配。KMP咯。说起KMP的话,自从大一上学C语言开始就有所了解,但是只知道它的用途和大概原理,从没下过功夫落实到具体的代码上。写这篇东西,依然只是把别人的想法和代码记录下来。
· KMP算法详解
· 代码与优化方法
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
模式匹配。KMP咯。说起KMP的话,自从大一上学C语言开始就有所了解,但是只知道它的用途和大概原理,从没下过功夫落实到具体的代码上。写这篇东西,依然只是把别人的想法和代码记录下来。
· KMP算法详解
· 代码与优化方法
class Solution { public: int strStr(string haystack, string needle) { if (haystack.empty()) return needle.empty() ? 0 : -1; if (needle.empty()) return 0; int i = 0, j = 0; vector<int> next(needle.length() + 1); getNext(next, needle); while (i != haystack.length()) { while (j != -1 && haystack[i] != needle[j]) j = next[j]; ++i; ++j; if (j == needle.length()) return i - j; } return -1; } private: void getNext(vector<int> &next, string &needle) { int i = 0, j = -1; next[i] = j; while (i != needle.length()) { while (j != -1 && needle[i] != needle[j]) j = next[j]; next[++i] = ++j; } } };
相关文章推荐
- openfire无法启动服务-------解决方案
- Scatter file
- POJ 1258 Agri-Net(最小生成树prim算法)
- quick 3.3final 编译成功 运行出错的问题
- -webkit-filter属性用来干什么
- 中日韩教科书中的历史
- 《Objective-C基础教程》第8章 Foundation Kit 介绍
- 继上一篇文章,由于本地限制,等后续整理在一起
- Chrome浏览器中的网上应用店如何加载
- mysql多字段唯一索引
- Java int和integer的区别
- div+css3纯手工制作登录页
- 任务单案例一
- Ubuntu系统下的Hadoop集群(6)_Hadoop安装配置简略教程
- 浅谈C/C++内存泄漏及其检测工具
- POJ 3620 Avoid The Lakes【DFS】
- java程序由mysql转到sqlserver时在浮点数处理上遇到的错误
- UVA 11584 Partitioning by Palindromes 划分回文串 (Manacher算法)
- Java DecimalFormat 用法
- 实际iOS编程中遇到的自定义导航栏按钮,导致手势返回失效的解决方法