编程之美 - 字符串移位包含

问题描述:
两个字符串s1, s2,将s1循环位移,判断s2是否被包含在其中。
例如:s1 = "ABCD"  s2= "CDA"  将s1循环位移后得到BCDA,s2被包含在s1循环位移后的字符串中。

思路 1:
将s1移位一次,然后与s2比较一次。如果字符串比较长,效率很低。

思路 2:
假设保留s1移位的结果,
例如:s1 = "ABCD"  
位移一次  s1 = "ABCDA"
位移二次  s1 = "ABCDAB"
位移三次  s1 = "ABCDABC"
位移四次  s1 = "ABCDABCD"

位移4次后,s1变成了 s1+s1,  利用这个特点直接判断s2是否是    s1+s1的字串。


代码:(方法2)

#include <iostream>

using namespace std;

bool find(char* src, char* dst)
{
	int lens = 0, lend = 0;
	char* p2src = NULL;
	bool find = false;

	if ((NULL == src) || (NULL == dst))
		return false;

	lens = strlen(src);
	lend = strlen(dst);

	if (lend > lens) return false;

	p2src = new char[lens*2+1];
	memcpy(p2src, src, lens);
	memcpy(p2src+lens, src, lens);
	p2src[lens*2] = '\0';

	if (NULL == strstr(p2src, dst))
	{
		find = false;
		cout << dst << " Not exist in " << src << endl;
	}
	else
	{
		find = true;
		cout << dst << " exist in " << src << endl;
	}
	delete[] p2src;
	p2src = NULL;

	return find;
}


void main()
{
	int i = 0;
	//char* str = "ABCDE";
	//char* dst = "DEAB";

	char* str = "ABCDEF";
	char* dst = "DEAB";

	find(str, dst);
	cin >> i;
}








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值