※上海交通大学 Coincidence(java)(动态规划)(LCS)

题目描述
Find a longest common subsequence of two strings.
输入描述:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
输出描述:
For each case, output k – the length of a longest common subsequence in one line.
示例1
输入
复制
abcd
cxbydz
输出
复制
2

LCS:

首先将要看到如何运用动态编程查找两个 DNA 序列的最长公共子序列(longest common subsequence,LCS)。发现了新的基因序列的生物学家通常想知道该基因序列与其他哪个序列最相似。查找 LCS 是计算两个序列相似程度的一种方法:LCS 越长,两个序列越相似。

子序列中的字符与子字符串中的字符不同,它们不需要是连续的。例如,ACE 是 ABCDE 的子序列,但不是它的子字符串。请看下面两个 DNA 序列:

S1 = DE>GCCCTAGCGDE>
S2 = DE>GCGCAATGDE>
这两个序列的 LCS 是 GCCAG。(请注意,这仅是一个 LCS,而不是唯一的 LCS,因为可能存在其他长度相同的公共子序列。这种最优化问题和其他最优化问题的解可能不止一个。)
import java.io.*;
import java.util.*;
public class Main
{
    public static void main(String[] args){
    	try {
	        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
	        char[] ch1 = br.readLine().toCharArray();
	        char[] ch2 = br.readLine().toCharArray();
	        int len1 = ch1.length;
	        int len2 = ch2.length;
	        int[][] dp = new int[len1+1][len2+1];
	        for(int i = 0; i < len1; i++) {
	        	for(int j = 0; j < len2; j++) {
	        		if(ch1[i] == ch2[j]) dp[i+1][j+1] = dp[i][j] + 1;
	        		else dp[i+1][j+1] = Math.max(dp[i+1][j], dp[i][j+1]);
	        	}
	        }
	        System.out.println(dp[len1][len2]);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
}
发布了231 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104183734