JSFiddle - React, Tailwind, and code Playground

longestPalindromeSubstring original

by Yurii Predborskyi

JavaScript

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
    function isPalindrome(word) {
        return word === word.split('').reverse().join('');
    }
    
    let res = '';
    let start = 0, finish = s.length;
    while (start < s.length) {
        let word = s.substring(start, finish);
        if (word.length <= res.length || finish <= start) {
            start++;
            finish = s.length;
            continue;
        }
        if (word.length > res.length && isPalindrome(word)) {
            res = word;
            start++;
            finish = s.length;
            if (finish - start <= res.length) {
                break;
            }
            continue;
        }
        finish--;
    }
    return res;
};

let test = "civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth";
console.log(longestPalindrome(test));