zoukankan      html  css  js  c++  java
  • JAVA最长公共子序列

    题目描述

    使用动态规划算法求两个序列的最长公共子序列,需构造一条最长公共子序列。

    输入

    每组输入包括两行,每行包括一个字符串。

    输出

    两个字符序列的一条最长公共子序列。(输入已确保最长公共子序列的唯一性)

    样例输入 Copy

    acdbxx
    ccdxx

    样例输出 Copy

    cdxx

    package lianxi5;
    
    import java.util.Scanner;
    /*
     * 最长公共子序列
     */
    public class Main18 {
    	public static void main(String[] args) {
    		Scanner sc=new Scanner(System.in);
    		String str1=sc.nextLine();
    		String str2=sc.nextLine();
    		char st1[]=new char[str1.length()];
    		char st2[]=new char[str2.length()];
    		
    		for(int i=0;i<str1.length();i++) {
    			st1[i]=str1.charAt(i);
    		}
    		for(int i=0;i<str2.length();i++) {
    			st2[i]=str2.charAt(i);
    		}
    		maxCommonChar(st1,st2);
    	
    	}
     
    
    public static void maxCommonChar(char [] a, char [] b){  
            int m = a.length;  
            int n = b.length;  
            int [][] len = new int[m + 1][n + 1];
            int [][] flags = new int[m + 1][n + 1];
            for(int i = 0; i <= m - 1; i++){
                for(int j = 0; j <= n - 1; j++){  
                    if(a[i] == b[j]){
                        len[i + 1][j + 1] = len[i][j] + 1;  
                        flags[i + 1][j + 1] = 1; 
                    }else if(len[i + 1][j] >= len[i][j + 1]){  
                        len[i + 1][j + 1] = len[i + 1][j];  
                        flags[i + 1][j + 1] = 2;  
                    }else{  
                        len[i + 1][j + 1] = len[i][j + 1];  
                        flags[i + 1][j + 1] = 3;  
                    }  
                }  
            }  
            int k = len[m][n];
            char [] commonChars = new char[k];
            int i = m, j = n; 
            for(;i > 0 && j > 0;){  
                if(flags[i][j]==1){
                    commonChars[k - 1] = a[i - 1];  
                    k--;  
                    i--;  
                    j--;  
                }else if(flags[i][j] == 2){  
                    j--; 
                }else{  
                    i--;  
                }  
            }   
         
            for(int l = 0; l <= len[m][n] - 1; l++){  
                System.out.print(commonChars[l]);  
            }  
    }  
    }
  • 相关阅读:
    vue-cil和webpack中本地静态图片的路径问题解决方案
    vue-cil 中的配置分析
    webpack中mainifest.js vendor.js app.js 三者的区别
    css 中可以继承的属性
    有关正则表达式的Js方法(replace)
    css 常用的几种垂直居中(包括图片)
    如何在Vue中建立全局引用或者全局命令
    删除数组中多个不连续的数组元素的正确姿势
    数据库
    代码片段
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13309573.html
Copyright © 2011-2022 走看看