-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcs.js
53 lines (40 loc) · 1.3 KB
/
lcs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
const lcs = (foo, bar) => {
const generate2DArray = (x, y) => {
let lenOfX = x.length, lenOfY = y.length
let arr = []
// init 2d-array arr
for(let i=0; i<lenOfX; i++){
arr[i] = []
for(let j=0; j<lenOfY; j++){
arr[i][j] = 0
}
}
// rebuild arr with dynamic programming
for(let i=1; i<lenOfX; i++){
for(let j=1; j<lenOfY; j++){
arr[i][j] =
x.charAt(i-1) === y.charAt(j-1)
? (arr[i-1][j-1] + 1)
: Math.max(arr[i-1][j], arr[i][j-1])
}
}
// the biggest number is the length of LCS
return arr
}
// collect LCS with traceback approach
const logLcs = (arr, x, y) => {
let tempArr = []
let i = x.length-1, j = y.length-1;
while(i>=0 && j>=0){
x.charAt(i) === y.charAt(j)
? (tempArr.push(x.charAt(i)) && i-- && j--)
: (arr[i-1][j] > arr[i][j-1] ? i-- : j--)
}
return tempArr.reverse().join(',')
}
let arr = generate2DArray(foo, bar);
return logLcs(arr, foo, bar);
}
console.log(lcs('12345', '1245'))
// 1,2,4,5