solution with Javascript


  • 0
    L

    I think the key saving time is the reverse string created at first, which is used to check the substring is right.

    here is my solution:

    /**
     * @param {string} s
     * @return {string}
     */
    var longestPalindrome = function(s) {
        
        var result = s[0];
    
        var array = s.split('');
        var reverseString = s.split('').reverse().join('');
        var len = s.length;
    
        array.forEach(function(letter, index) {
            if (result.length > len - index) return;
            var lastIndex = s.lastIndexOf(letter);
            if (lastIndex === -1) return;
            while (lastIndex > index && lastIndex - index >= result.length) {
                var ret = check(index, lastIndex);
                if (ret && ret.length >= result.length) {
                    result = ret;
                    return;
                }
                lastIndex = s.lastIndexOf(letter, lastIndex - 1);
            }
        });
    
        function check(index, lastIndex) {
    
            var str = s.slice(index, lastIndex+1);
            var reverseStr = reverseString.substring(len - lastIndex - 1, len - index);
    
            if (str === reverseStr) {
                return str;
            }
        }
    
        return result;
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.