zoukankan      html  css  js  c++  java
  • 求两个字符串的最长公共字串(连续)

    题目描述:

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

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

    思路一:

    从字符串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]='';
    				}
    			}
    		}
    	}	
    	return max_str;
    }
    
    
  • 相关阅读:
    链表的一些规律总结
    acclib的尝试
    初入指针
    在一个堆成矩阵中的循环判断(井字棋游戏)
    初学c语言的小套路汇总
    在循环中计算式一正一负的处理
    最大公约数的计算方法
    大数加法
    大数乘法
    复制可见区域到新表
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3221691.html
Copyright © 2011-2022 走看看