求两字符串的最长公有串 —— 我的“平移算法”

 

原创文章,转载请注明出处!

问题:
求A和B两个字符串的最长公共子串,并输出其长度。

分析:
我还没看过系统算法方面的书,不过我想以后要加强了,:-),目前我想到用“平移法”来计算最长公有串,还未分析过其它算法,不过我想,这个速度应该还不错。

原理:把两个字符串想像成两板木板,木板A短于木板B,让木板A在木板B上平移,从而找到垂直方向的公共字符串,进尔求得最长公有串

分解1

+-------------+
|     A       |
+-------------+
         +---------------------+
         |          B          |
         +---------------------+
         ^
         i     

分解2

                      +-------------+
                      |     A       |
                      +-------------+
         +---------------------+
         |          B          |
         +---------------------+
                      ^
                      i
代码实现:
#include "stdafx.h"
#include <iostream>
using namespace std;

void get_substr(char* strA, char* strB, char* strSub);

int _tmain(int argc, _TCHAR* argv[])
{
	char* a = "hello, i am =weisunding!";
	char* b ="my name is -weisunding, you who??";
	char  substr[100] = {0};

	get_substr(a, b, substr);

	cout<<substr<<endl;
	
	system("pause");
	return 0;
}

//核心代码
void get_substr(char* strA, char* strB, char* strSub)
{
	int sub_index = 0;
	int sub_len = 0;

	// strlen(s1) < strlen(s2)
	char* s1 = strA;
	char* s2 = strB;

    if (strlen(strA) > strlen(strB))	
		swap(s1, s2);
	
    int len1 = strlen(s1);
	int len2 = strlen(s2);
	int x1,x2;

	for(int i = 1 - len1; i < len2; ++i)
	{
		if (i <= 0)
		{
			x1 = i + len1 - 1;
			x2 = 0;                           
		}
		else
		{
			x1 = 0;
			x2 = i;
if (len2 - x2 < sub_len)
    break; }
int len = 0; while( (x1 < len1) || (x2 < len2)) { if ( s1[x1] == s2[x2]) { ++len; if (len > sub_len) { sub_index = x2; //the last index sub_len = len; } } else { len = 0; } ++x1; ++x2; } } if (sub_len) strncpy(strSub, s2 + sub_index - (sub_len - 1) , sub_len); }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值