算法导论之第十五章-动态规划之最长公共子序列

public class Test {

	public static String[][] common = new String[0][0];
	public static void main(String[] args) {
		String s1 = "AHKZICNYEANDKCLPDHUYYGFQHCJDIHUNAJIDHAIHVNIAHUANZJIANCMAUCUHDANAUDUAIHDINU";
		String s2 = "HSIMNCUHUHAHIOXZBQBAYDGIANCMAHISALICJAUHDHUABCPAKUQHNVNAUHAUDNAUDHAUHDUAHDUIN";
		
		//String s1 = "AHKZICNYEANDKCLPDHUYYG";
		//String s2 = "HSIMNCUHUHAHIOXZBQBAYD";
		common = new String[s1.length()][s2.length()];
		System.out.println(getLongestCommon(s1,s2,s1.length(),s2.length()));
	}

	public static String getLongestCommon(String s1, String s2, int l1, int l2) {
		if(l1==0||l2==0) {
			return "";
		}
		if(common[l1-1][l2-1]!=null) {
			return common[l1-1][l2-1];
		}
		if(s1.charAt(l1-1)==s2.charAt(l2-1)) {
			common[l1-1][l2-1] = getLongestCommon(s1,s2,l1-1,l2-1)+s1.charAt(l1-1);
			return common[l1-1][l2-1];
		}
		String sr1 = getLongestCommon(s1,s2,l1-1,l2);
		String sr2 = getLongestCommon(s1,s2,l1,l2-1);
		common[l1-1][l2-1] = sr1.length()>sr2.length()?sr1:sr2;
		return common[l1-1][l2-1];
	}
}

猜你喜欢

转载自blog.csdn.net/qq_33321609/article/details/87185699
今日推荐