前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++版 - Leetcode 28.Implement strStr() 解题报告【C库函数strstr()模拟-字符串中子串首次出现的地址】

C++版 - Leetcode 28.Implement strStr() 解题报告【C库函数strstr()模拟-字符串中子串首次出现的地址】

作者头像
Enjoy233
发布2019-03-05 14:30:32
3420
发布2019-03-05 14:30:32
举报

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代码:

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年05月07日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档