Palindrom Detection II


This is the former implementation of palindrom (I know it’s not typical): Palindrom detection by building clusters.

In this article I propose a much simpler solution which builds two string and compares them by _isPalindrom method.

String.prototype.longestPalindrome = function() {
    function _isPalindrome(a,b) {
        var _a = a.split('').reverse().join('');
        return _a == b;
    }
    var longestVal = "";
    var middle = Math.round(this.length/2);
    if( this.length == 1 ) return this;
    for( var i=1; i<this.length; i++ ) {
        for( var offset = 1; offset<middle; offset++ ) {
            var bBreak = false;

            //detect the borders
            var start0 = i-offset, end0 = i+1;
            var start1 = i, end1 = i+offset+1;

            //word boundary reached?
            if( start0 < 0 ) {
                start0 = 0;
                bBreak = true;
            }
            if( end1 > this.length ) {
                end1 = this.length;
                bBreak = true;
            }

            //build the string and evaluate it with _isPalindrom function
            var str0 = this.substring(start0, end0), str1 = this.substring(start1, end1);
            if( _isPalindrome( str0, str1 ) ) {
                if( str0.length+str1.length-1 > longestVal.length )
                    longestVal = str0 + str1.substr(1);
            }
            if( bBreak ) //no more characters available
                break;
        }
    }
    return longestVal;
}

console.log( new String("---evacaniseebeesinacave***").longestPalindrome() ); //yields 'evacaniseebeesinacave'

Leave a comment