Simple O(n^2) solution using JavaScript


#1

Simple O(n^2) solution using JavaScript

longestPalindrome : function(A){
    let max = ''
    for (let i = 1; i <= A.length; i ++) {
        // look for even palindromes
        let low = i - 1,  high = i;
        while (low >= 0 && high < A.length && A[low] === A[high]) {
            if (max.length < high - low + 1) {
                max = A.substr(low, high - low + 1)
            }
            low --; high ++;
        }
        // look for odds palindromes
        low = i - 1, high = i + 1;
        while (low >= 0 && high < A.length && A[low] === A[high]) {
            if (max.length < high - low + 1) {
                max = A.substr(low, high - low + 1)
            }
            low --; high ++;
        }
    }
    return max || A[0];
}