두 개의 리터럴 배열을 받는 JavaScript 함수를 작성해야 합니다. 이를 arr1 및 arr2라고 합시다.
함수는 배열에서 리터럴의 가장 긴 공통 행을 찾아야 합니다. 함수는 마침내 해당 리터럴의 배열을 반환해야 합니다.
예:
입력 배열이 -
인 경우const arr1 = ['a', 'b', 'c', 'd', 'e']; const arr2 = ['k', 'j', 'b', 'c', 'd', 'w'];
그러면 출력 배열은 -
여야 합니다.const output = ['b', 'c', 'd'];
예시
다음은 코드입니다 -
const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['k', 'j', 'b', 'c', 'd', 'w'];
const longestCommonSubsequence = (arr1 = [], arr2 = []) => {
let str1 = arr1.join('');
let str2 = arr2.join('');
const arr = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null));
for (let j = 0; j <= str1.length; j += 1) {
arr[0][j] = 0;
}
for (let i = 0; i <= str2.length; i += 1) {
arr[i][0] = 0;
}
for (let i = 1; i <= str2.length; i += 1) {
for (let j = 1; j <= str1.length; j += 1) {
if (str1[j - 1] === str2[i - 1]) {
arr[i][j] = arr[i - 1][j - 1] + 1;
} else {
arr[i][j] = Math.max(
arr[i - 1][j],
arr[i][j - 1],
);
}
}
}
if (!arr[str2.length][str1.length]) {
return [''];
}
const res = [];
let j = str1.length;
let i = str2.length;
while (j > 0 || i > 0) {
if (str1[j - 1] === str2[i - 1]) {
res.unshift(str1[j - 1]);
j -= 1;
i -= 1;
}
else if (arr[i][j] === arr[i][j - 1]) {
j -= 1;
}
else {
i -= 1;
}
}
return res;
};
console.log(longestCommonSubsequence(arr1, arr2)); 출력
다음은 콘솔의 출력입니다 -
['b', 'c', 'd']