求两个字符串的公共子串

求两个字符串的公共子串....

#include <iostream>
using namespace std;

/*
	a b c d a b a b
a   1 0 0 0 0 0 1 0
b   0 2 0 0 0 1 0 1
c    0 0 3 0 0 0 0 0
a    1 0 0 0 1 0 1 0
特征数组的值:等于左上角+1 
*/
typedef struct
{
	int max_i;//存储最大公共子串的末尾位置 
	int max_j;
	int max_num;
}data_node;

data_node* strFind(const char* str1,const char *str2)
{
	int len1=strlen(str1);
	int len2=strlen(str2);
	
	int **array_flag;	//特征数组 
	array_flag=new int*[len1];
	for(int i=0;i<len1;i++)
	{
		array_flag[i]=new int[len2];
	}
	
	data_node *mydata=new data_node;
	mydata->max_i=0;
	mydata->max_j=0;
	mydata->max_num=-1;
	
	for(int i=0;i<len2;i++)//第一行 
	{
		if(str1[0]==str2[i])
		{
			array_flag[0][i]=1;
			
			mydata->max_i=0;
			mydata->max_j=i;
			mydata->max_num=1;
		}
		else
		{
			array_flag[0][i]=0;
		}
	}

	for(int i=0;i<len1;i++)//第一列 
	{
		if(str1[i]==str2[0])
		{
			array_flag[i][0]=1;
		}
		else
		{
			array_flag[i][0]=0;
		}
	}
	
	for(int i=1;i<len1;i++)//从第二行、第二列开始 
	{
		for(int j=1;j<len2;j++)	
		{
			if(str1[i]==str2[j])
			{
				array_flag[i][j]=array_flag[i-1][j-1]+1;//如果相等,则等于左上角加+1 
				
				if(array_flag[i][j]>mydata->max_num)
				{
					mydata->max_num=array_flag[i][j];
					mydata->max_i=i;
					mydata->max_j=j;
				}
			}
			else
			{
				array_flag[i][j]=0;
			}
		}
	}

	return mydata;
}

int main(int argc, char *argv[])
{
	char *str1="kjabcabab";
	char *str2="aabac";
	
	data_node *tempNode=strFind(str1,str2);
	cout<<"最大公共子串的长度为:"<<tempNode->max_num<<endl;
	cout<<"在str1中的位置:"<<tempNode->max_i-tempNode->max_num+1<<endl;
	cout<<"在str2中的位置:"<<tempNode->max_j-tempNode->max_num+1<<endl;
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值