题解 | #最长公共子序列(二)#
最长公共子序列(二)
https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11
import java.util.*; public class Solution { /** * longest common subsequence * @param s1 string字符串 the string * @param s2 string字符串 the string * @return string字符串 */ public String LCS (String s1, String s2) { // write code here if(s1.equals("") || s2.equals("")) return "-1"; int m = s1.length(); int n = s2.length(); int dp[][] =new int[m+1][n+1]; for(int i = 1 ; i <= m ; i++){ for(int j = 1 ; j <= n ; j++){ if(s1.charAt(i-1) == s2.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]); } } } StringBuilder s = new StringBuilder(""); while(m != 0 || n != 0 ){ while( m > 0 && dp[m][n] == dp[m-1][n] ) m--; while(n > 0 && dp[m][n] == dp[m][n-1] ) n--; if(m>0){ s.append(s1.charAt(m-1)); m--; n--; } } s = s.reverse(); String res = s.toString(); return res.equals("")?"-1":res; } }