Leetcode 28.Implement strStr() 解题报告【C库函数strstr()模拟-字符串中子串首次出现的地址】
2016-05-07 08:57
477 查看
28. Implement strStr()
提交网址 https://leetcode.com/problems/implement-strstr/
Total Accepted: 105435 Total
Submissions: 422883 Difficulty: Easy
Implement
strStr( ).
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
分析:
对此问题,KMP是一个比较合适的解法...
AC代码:
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
using namespace std;
// LeetCode, Implement strStr()
// KMP 时间复杂度O(N+M),空间复杂度O(M)
class Solution {
public:
int strStr(const string& haystack, const string& needle) {
return kmp(haystack.c_str(), needle.c_str());
}
private:
/*
* @brief 计算部分匹配表,即next数组
**
@param[in] pattern:模式串
* @param[out] next:next数组
* @return:无
*/
static void compute_prefix(const char *pattern, int next[]) {
int i;
int j = -1;
const int m = strlen(pattern);
next[0] = j;
for (i = 1; i < m; i++) {
while (j > -1 && pattern[j + 1] != pattern[i]) j = next[j];
if (pattern[i] == pattern[j + 1]) j++;
next[i] = j;
}
}
/*
* @brief KMP
**
@param[in] text
* @param[in] pattern
* @return 失败则返回-1,成功匹配时返回第一次匹配的位置
*/
static int kmp(const char *text, const char *pattern) {
int i;
int j = -1;
const int n = strlen(text);
const int m = strlen(pattern);
if (n == 0 && m == 0) return 0; /* "", "" */
if (m == 0) return 0; /* "a", "" */
int *next = (int*)malloc(sizeof(int) * m);
compute_prefix(pattern, next);
for (i = 0; i < n; i++) {
while (j > -1 && pattern[j + 1] != text[i]) j = next[j];
if (text[i] == pattern[j + 1]) j++;
if (j == m - 1) {
free(next);
return i-j;
}
}
free(next);
return -1;
}
};
// 下面是测试
int main()
{
Solution sol;
string str1="To be or not to be";
string str2="be";
cout<<sol.strStr(str1, str2)<<endl;
return 0;
}
相关文章推荐
- Linux(centOS6.5)下SVN的安装、配置及开机启动
- C++/Php/Python/Shell 程序按行读取文件或者控制台
- NYOJ-93汉诺塔(三)
- 《safe+》离线密码更安全,一键修改最方便
- java多线程技能基础
- Android系统自带样式(@android:style/)
- POJ3233 Matrix Power Series构造矩阵解决问题
- C++3层架构的UML例图
- Linux的原子操作与同步机制
- JAX-RS入门 一 :基础
- jqeury中ajax的表单实现异步提交
- excle中字符串选取#好读书,读好书#--好读书,读好书
- 我最喜欢的SQL分页查询方法
- 关于android核心组件Activity的一些总结
- 线程进程通信和同步方式
- 【android】 Unable to open content: file:///sdcard/hello.3gp 3gp视频不能播放
- 【HUSTOJ】1088: 查找“支撑数”
- Android Preference 须知
- 【HDU 3652】B-number
- android基础总结篇之四:Service完全解析