5. Longest Palindromic Substring

/**
 * @param {string} s
 * @return {string}
 */
 /**
 time: O(n^3)
 space: O(n)
*/
var longestPalindrome = function(s) {
    let max = s[0];

    for (let i = 0; i < s.length; i++) {
        for (let j = i; j < s.length; j++) {
            if (isPalindrome(s, i, j)) {
                if (j - i + 1 >= max.length) {
                    max = s.substring(i, j + 1);
                }
            }
        }
    }

    return max;
};

function isPalindrome(str, s, e) {
    while (s <= e) {
        if (str[s] !== str[e]) {
            return false;
        }
        s++;
        e--;
    }

    return true;
}

Last updated