题解 | #最长公共子序列(二)#
最长公共子序列(二)
http://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字符串
*/
int width = s2.length();
int[][] dp = new int[height+1][width+1];
for(int i = 1;i < dp.length;i++){
for(int j = 1;j<dp[0].length;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]);
}
}
stack.push(s1.charAt(height-1));
height --;
width --;
height--;
}else{
width --;
}
}
}
if(stack.isEmpty()){
return "-1";
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.toString();
}
}
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) {
//关于dp数组的部分和前面思路一样
int height = s1.length();int width = s2.length();
int[][] dp = new int[height+1][width+1];
for(int i = 1;i < dp.length;i++){
for(int j = 1;j<dp[0].length;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]);
}
}
}
// 关于取出一样的数组下标用栈这个数据结构我觉得比较合适
Stack<Character> stack = new Stack<Character>();
//从dp二维数组的最后一个判断
while(dp[height][width] != 0){
// 如果下标代表的字符一致时直接压
if(s1.charAt(height-1) == s2.charAt(width-1)){stack.push(s1.charAt(height-1));
height --;
width --;
}else{
//不一样直接找从哪个下标来的
if(dp[height-1][width] > dp[height][width-1]){height--;
}else{
width --;
}
}
}
if(stack.isEmpty()){
return "-1";
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.toString();
}
}