首页 > 专题系列 > Java解POJ > POJ 1458 Common Subsequence [解题报告] Java
2013
11-09

POJ 1458 Common Subsequence [解题报告] Java

Common Subsequence

问题描述 :

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,…,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.

输入:

The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.

输出:

For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.

样例输入:

abcfbc         abfcab
programming    contest 
abcd           mnp

样例输出:

4
2
0

解题代码:

import java.util.Scanner;

public class Main{
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		while(in.hasNext()){
			String str1 = in.next();
			String str2 = in.next();
			int[][] DP = new int[str1.length()+1][str2.length()+1];
			int i;
			for(i=0;i<=str1.length();i++)
				DP[i][0] = 0;
			for(i=0;i<=str2.length();i++)
				DP[0][i] = 0;
			for(i=1;i<=str1.length();i++){
				for(int j=1;j<=str2.length();j++){
					if(str1.charAt(i-1) == str2.charAt(j-1))
						DP[i][j]=DP[i-1][j-1]+1;
					else
						DP[i][j]=Math.max(DP[i-1][j], DP[i][j-1]);
				}
			}
			System.out.println(DP[str1.length()][str2.length()]);
		}		
	}
}

  1. 给你一组数据吧:29 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1000。此时的数据量还是很小的,耗时却不短。这种方法确实可以,当然或许还有其他的优化方案,但是优化只能针对某些数据,不太可能在所有情况下都能在可接受的时间内求解出答案。

  2. 学算法中的数据结构学到一定程度会乐此不疲的,比如其中的2-3树,类似的红黑树,我甚至可以自己写个逻辑文件系统结构来。