求两个字符串的最长公共字串(连续)

题目描述:

输入两个字符串,求其的最长的公共的字串,这与最长公共子序列不一样

输出两字符串的最长公共字串

思路一:

从字符串A开始遍历,同时遍历字符串A,找到第一个与当前字符串A相同的字符,此时记下当前的pos,并同时遍历两字符串,

直到找到两字符串不相同的字符,记下其长度,与max比较,大则则将相同的子串copy到max_str中

C++实现

 

#include <stdio.h>
#include <string.h>
char* longest_str(char* one, char* two)
{
	int i=0, j=0, max=0, m=0;  //m:record the number of equal characters
	int len_one = strlen(one);
	int len_two = strlen(two);
        char *max_str = (char*)malloc(len_one+1);
	memset(max_str, 0, len_one+1);	
	
	for(i=0; i<len_one; i++)
	{
		for(j=0; j<len_two; j++)
		{
			if(one[i]==two[j])  //the first equal character
			{
				for(m=0; one[i+m]==two[j+m]; m++); //m equal characters
				if(m>max)	//compare m and max
				{
					max = m;
					strncpy(max_str, &two[j], m);  //copy m characters
					max_str[m]='\0';
				}
			}
		}
	}	
	return max_str;
}

 

 

 

posted @ 2013-07-28 21:09  jlins  阅读(524)  评论(0编辑  收藏  举报