| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 633 人关注过本帖
标题:求助!求两个串的最长公共子序列
只看楼主 加入收藏
tracycc
Rank: 1
等 级:新手上路
帖 子:20
专家分:0
注 册:2006-7-27
收藏
 问题点数:0 回复次数:0 
求助!求两个串的最长公共子序列
想要求出两个串的最长公共子序列(不是子串,子序列可以是不连续的),以下的这个算法(用的是lcs,动态规划)能求出一个最长公共子序列,是badb,长度是4.可是这两个串bacdbd 和dbcbadb的最长公共子序列有三个,分别是badb,bcbd,bcdb,长度都是4,如何把它们都求出来??先谢谢大家了!

程序代码:
import *;
public class ys
{
    static int length = 0; //保存最长公共子序列的长度
    static String  str_same = "";  //保存最长公共子序列
    static int k = 0;
    public static void main(String args[])
    {
        char x[],y[];
        String str_x="bacdbd",str_y="dbcbadb"; //原始比较的两个串
        try{
            str_x=" "+str_x;        
            str_y=" "+str_y;
        } catch(Exception e){
            e.printStackTrace();
        }
        x=str_x.toCharArray();
        y=str_y.toCharArray();
        int b[][]=new int[x.length][y.length];
        lcsLength(x,y,b);
        lcs(x.length-1,y.length-1,x,b);
        System.out.println("length:"+length);
        System.out.println("str_same:"+str_same);
        System.out.print("\n");
    }
    public  static void lcsLength(char []x,char []y,int [][]b)
    {
        int xMaxIndex=x.length-1;
        int yMaxIndex=y.length-1;
        int count[][]=new int[xMaxIndex+1][yMaxIndex+1];
        for(int i=0;i<=xMaxIndex;i++)
        {
            count[i][1]=0;
        }
        for(int i=0;i<=yMaxIndex;i++)
        {
            count[0][i]=0;
        }
        for(int i=1;i<=xMaxIndex;i++)
        for(int j=1;j<=yMaxIndex;j++)
        {
            if(x[i]==y[j]) //如果相等 则对角线加一
            {
                count[i][j]=count[i-1][j-1]+1;
                b[i][j]=1;
            }
            //如果不等,则比较上方和左方,取最大值
            else if(count[i-1][j]>=count[i][j-1]) 
            {
                count[i][j]=count[i-1][j];
                b[i][j]=2;
            }
            else 
            {
                count[i][j]=count[i][j-1];
                b[i][j]=3;
            }
            
        }
    }
    public static void lcs(int i,int j,char []x,int [][]b)
    {
        if(i==0||j==0)
        {
            return;
        }
        if(b[i][j]==1)
        {
            length ++;           
            lcs(i-1,j-1,x,b);
            str_same += x[i];
        }
        else if(b[i][j]==2)
        {
            
            lcs(i-1,j,x,b);
            
        }
        else if(b[i][j]==3)
        {
            lcs(i,j-1,x,b);
        }
    }
}
搜索更多相关主题的帖子: 序列 
2008-05-09 12:41
快速回复:求助!求两个串的最长公共子序列
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016157 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved