# 动态规划问题（2）——寻找最长公共子串

### 题目：

``````var str1="abcdefg";
var str2="xyzabcd";
``````

### 动态规划

1. 从底部开始解决问题，将所有小问题解决掉，然后合并成一个整体的解决方案。
2. 使用一个数组建立一张表，用于存放被分解成众多子问题的解。

``````var arr = new Array(str1.length + 1);
for (var i = 0; i <= str1.length + 1; i++) {
arr[i] = new Array(str2.length + 1);
for (var j = 0; j <= str2.length + 1; j++) {
arr[i][j] = 0;
}
}
``````

image

``````var maxLen = 0;
var index = 0;
for(var i = 0; i <= str1.length; i++){
for(var j = 0; j <= str2.length; j++){
if(i == 0 || j == 0){
arr[i][j] = 0
}else{
if (str1[i] == str2[j] && str1[i - 1] == str2[j - 1]) {
arr[i][j] = arr[i - 1][j - 1] + 1;
}else{
arr[i][j] = 0;
}
}
if(arr[i][j] > maxLen){
maxLen = arr[i][j];
index = i;
}
}
}
``````

``````var str = "";
if(maxLen == 0){
return "";
}else{
for(var k = index - maxLen; k < maxLen; k++){
str += str1[k];
}
return str;
}
``````

``````function LCS(str1, str2){
var maxLen = 0;
var index = 0;

var arr = new Array();
for (var i = 0; i <= str1.length + 1; i++) {
arr[i] = new Array();
for (var j = 0; j <= str2.length + 1; j++) {
arr[i][j] = 0;
}
}

for(var i = 0; i <= str1.length; i++){
for(var j = 0; j <= str2.length; j++){
if(i == 0 || j == 0){
arr[i][j] = 0
}else{
if (str1[i] == str2[j] && str1[i - 1] == str2[j - 1]) {
arr[i][j] = arr[i - 1][j - 1] + 1;
}else{
arr[i][j] = 0;
}
}
if(arr[i][j] > maxLen){
maxLen = arr[i][j];
index = i;
}
}
}

var str = "";
if(maxLen == 0){
return "";
}else{
for(var k = index - maxLen; k < maxLen; k++){
str += str1[k];
}
return str;
}
}
var str1="abcdefg";
var str2="xyzabcd";
LCS(str1, str2)     // abcd
``````