Implement strStr()
2016-01-05 22:36
120 查看
每日算法——leetcode系列
问题 Implement strStr()
Difficulty: EasyImplement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution { public: int strStr(string haystack, string needle) { } };
翻译
实现strStr()
难度系数:简单实现strStr()。
返回匹配时的第一个索引, 如果没有匹配的就返回-1。(感觉原文用针和草堆来形容带诙谐)
思路
strstr经典题。
假设:
遍历到的needle索引为j, haystack索引为i+j, needle,haystack长度分别为m,n
- 暴力法
遍历haystack和needle,如果haystack[i+j] == needle[j](匹配), 则 j++;
如果不等于(失配),i++, j = 0 T(O) = m * n
- KMP
这个得专门写一篇总结的文章。
还有Linux的grep, BM算法
代码
class Solution { public: int strStr(string haystack, string needle) { return strStrKMP(haystack, needle); } private: // brute-force int strStrBF(string haystack, string needle) { if (needle.empty()){ return 0; } int i = 0; int hSize = (int)(haystack.size()); int nSize = (int)(needle.size()); if (hSize < nSize){ return -1; } while(i < hSize){ int j = 0; if (haystack[i + j] == needle[j]){ j++; }else{ i++; j = 0; } if (j >= nSize){ return i; } } return -1; } // KMP int strStrKMP(string haystack, string needle) { if (needle.empty()){ return 0; } int i = 0; int hSize = static_cast<int>(haystack.size()); int nSize = static_cast<int>(needle.size()); if (hSize < nSize){ return -1; } vector<int> next(nSize, -1); calcNext(needle, next); int j = 0; while (i < hSize) { if (j == -1 || haystack[i] == needle[j]){ i++; j++; }else{ j = next[j]; } if (j >= nSize){ return i - nSize; } } return -1; } void calcNext(const string& needle, vector<int> &next){ int nSize = static_cast<int>(needle.size()); int i = 0; int j = -1; while (i < nSize - 1) { if (j == -1 || needle[i] == needle[j]){ i++; j++; next[i] = j; }else{ j = next[j]; } } } };
相关文章推荐
- 蓝桥杯 最大子阵 (DP)
- [Android] hardcoded string should use @string警告
- Linux内核tag分析
- IIS Server Farms集群负载
- lintcode : 平衡二叉树
- easypr车牌识别开源项目学习(一)
- 前端开发入门:yahoo军规性能优化
- UVA 294 - Divisors 因子个数
- Xcode7.x中安装Alcatraz
- C#中如何判断一个文件是否存在
- 剖析软件外包项目
- 剖析软件外包项目
- Android四大组件之Activity
- 剖析软件外包项目
- 以软件开发生命周期来说明不同的测试的使用情况
- 启动过程内存check和vmalloc大小设置
- Threading Module源码概述(二)
- 第六章(函数)编程题一
- 第三十九天-企业级生产场景全网备份与集群架构解决方案图解
- 怎么和产品沟通