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

题目描述:

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

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

思路一:

从字符串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;
}

 

 

 

原文链接: https://www.cnblogs.com/dyllove98/p/3221691.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/97602

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午4:20
下一篇 2023年2月10日 上午4:21

相关推荐