Skip to content

Instantly share code, notes, and snippets.

@kimbtech
Created November 19, 2018 13:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimbtech/4186e7afc6d60d34a2f901fbc971f30d to your computer and use it in GitHub Desktop.
Save kimbtech/4186e7afc6d60d34a2f901fbc971f30d to your computer and use it in GitHub Desktop.
A LCS Palindrome JS Code
function LCSPalindrome( string ){
//erstelle Array von chars, eins rueckwaerts
var s = string.split('');
var t = string.split('')
t = t.reverse();
//Erstelle zwei Matrizen fuer LCS
// JS ist hier komisch
var pl = [];
var way = [];
for( var i = 0; i < s.length+1; i++ ){
var inner = [];
var wi = [];
for( var j = 0; j < s.length+1; j++ ){
inner.push( 0 );
wi.push(-1);
}
pl.push( inner );
way.push(wi);
}
//Bereichne LCS
for( var i = 1; i < s.length+1; i++ ){
for( var j = 1; j < s.length+1; j++ ){
if (s[i-1] == t[j-1]){
pl[i][j] = pl[i-1][j-1] + 1;
way[i][j] = [i-1, j-1];
}
else{
pl[i][j] = Math.max(pl[i-1][j], pl[i][j-1]);
way[i][j] = pl[i-1][j] > pl[i][j-1] ? [i-1, j] : [i, j-1];
}
}
}
//Zeichne Matrix
var a, b;
for( var i = 0; i < s.length+1; i++ ){
a = [' ', ' '];
b = [];
for( var j = 0; j < s.length+1; j++ ){
if( i == 0 && j < s.length ){
a.push( s[j] );
}
if( j == 0 ){
b.push( i > 0 ? s[i-1] : ' ' );
}
b.push( "" + pl[i][j] );
}
if( i == 0 ){
console.log(a);
}
console.log(b);
}
//Bestimme Sequenz
var x = s.length, y = s.length;
var seq = '';
do{
seq += typeof s[x] !== 'undefined' ? s[x] : '';
var p = way[x][y];
x = p[0];
y = p[1];
}while( typeof way[x] !== 'undefined' );
console.log( 'Sequenz: ' + seq );
return pl[s.length][s.length];
}
console.log( 'bab', LCSPalindrome( 'bab' ) );
console.log( 'ba', LCSPalindrome( 'ba' ) );
console.log( 'bababa', LCSPalindrome( 'bababa' ) );
/*
run:
> node ./A5_3.js
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment