微软100题(85)KMP_COUNT题

1.给出一个函数来复制两个字符串A和B。
字符串A的后几个字节和字符串B的前几个字节重叠。
分析:记住,这种题目往往就是考你对边界的考虑情况。
2.已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde的个数,
如果没有返回0,有的话返回子字符串的个数

1.解答:
memmove类似,如果有重叠,则考虑从后往前复制,以免覆盖导致字符丢失,还有就是考虑空等特殊情况的处理

2.解答:
方法一:KMP_count算法
#include<iostream>
#include<stdlib.h>
#include<vector>
using namespace std;

inline void NEXT(const string &T,vector<int> &next)
{
	//按模式串生成vector,next(T.size())
	next[0]=-1;
	int i=0;
	int j=-1;
	while(i<T.size()-1)
	{
		if (j==-1||T[i]==T[j])
		{
			++i;
			++j;
			next[i]=j;
		}
		else
			j=next[j];
	}
}
inline string::size_type COUNT_KMP(const string &S,
	const string &T)
{
	//利用模式串T的next函数求T在主串S中的个数count的KMP算法
	//其中T非空,
	vector<int> next(T.size());
	NEXT(T,next);
	string::size_type index,count=0;

	for(index=0;index<S.size();++index)
	{
		int pos=0;
		string::size_type iter=index;
		while(pos<T.size()&&iter<S.size()){
			if(S[iter]==T[pos]){
				++iter;++pos;
			}
			else	
			{
				if(pos==0) ++iter;
				else pos=next[pos-1]+1;
			}
		}
		if(pos==T.size()&&(iter-index)==T.size()) ++count;
		if(pos==T.size()&&(iter-index)>T.size()) index=iter-T.size()-1;
	}
	return count;
}
int main(int argc,char *argv[])
{
	string S="BAHHHBAHHHBA";
	string T="BA";
	string::size_type count=COUNT_KMP(S,T);
	cout<<count<<endl;
	system("PAUSE");
	return 0;
}


方法二:strstr 找到之后 des串往后移动一位,继续执行strstr
方法三:strncmp函数
int count_of_substr(const char* str, const char * sub) {
  int count = 0;
  char * p = str;
  int n = strlen(sub);
  while ( *p != ‘\0’ ) {
    if (strncmp(p, sub, n) == 0) count ++;
    p++;
  }
  return count;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值