Quantcast
Channel: Carl'Blog » c++
Viewing all articles
Browse latest Browse all 4

最长公共子串—-这个输出所有子串长度

0
0

给定两个字串,”abcedfghijk”与”abbcedfhgijk”,请编写程序,求两个字符串的最长公共子串。
这个是自己写的,不完善,代码应该对,各位自己测试。
有问题请留言,谢谢。

#include <iostream>
using namespace std;
void main()
{
	int *c=new int[7];//测试用
	int temp2=0;//测试数组标志
	string a="abcedfghijk";
	string b="abbcedfhgijk";
	for(int i=0;a[i]!='\0';i++)
	{
		int temp1=0,tmp=i;//temp1记录公共子串长度;tmp避免污染i,以便循环
		for(int j=0;b[j]!='\0';j++)
		{
			if(temp1>1&&a[tmp]!=b[j])//公共子串长度大于1的处理方式
			{
				c[temp2++]=temp1;//记录数据
				tmp=i;//恢复被污染tmp-------begin-----
				j--;//恢复污染j
				temp1=0;//恢复污染temp1
				continue;//-----------end------主要是测试这个公共子串后面是否还有符合条件公共子串
			}
			if(a[tmp]!=b[j]&&temp1==1)//公共子串长度等于1的处理方式
			{
				temp1=0;//归0-------begin-----
				tmp=i;//恢复被污染tmp
				j--;//恢复污染j
				continue;//-----------end------主要是跳过类似ab与ac这样的只有一个字母的公共子串
			}
			if(a[tmp]!=b[j]&&temp1==0)//公共子串长度等于0也就是从b[]寻找a[tmp]相同的第一个值
			{
				continue;
			}
			if(a[tmp]==b[j])//a[],b[]相等的字母情况处理
			{
				tmp++;//类似i++不过用tmp避免污染i
				temp1++;//公共子串长度+1
				if((a[tmp]=='\0'||b[j+1]=='\0')&&temp1>1)//处理类似测试a[],b[]末尾有相同字符串情况
				{
					c[temp2++]=temp1;//存储
					break;//末尾可以跳出循环
				}
			}
		}
	}
	for(int m=0;m<7;m++)//输出测试字符
		cout<<c[m]<<endl;
}

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images