My Ruby implementation slow. Any Improvements you see?


  • 0
    K
    # @param {String} s
    # @return {String}
    def longest_palindrome(s)
        max = [0,0]
        s.length.times do |i|
            s1, e1 = check_palindromic_starting_at(s, (i-1), (i+1))
            s2, e2 = check_palindromic_starting_at(s, (i-1), i)
            this_scope_max = (e1 - s1) >= (e2 - s2) ? [s1, e1] : [s2, e2]
            calc = -> (pair) { pair[1] - pair[0] }
            max = calc[this_scope_max] > calc[max] ? this_scope_max : max
        end
        s[(max[0]+1)..(max[1]-1)]
    end
    
    def check_palindromic_starting_at(str, prev_i, next_i)
        while str[prev_i] == str[next_i]    
            break if prev_i < 0 || next_i >= str.length
            prev_i -= 1
            next_i += 1
        end
        [prev_i, next_i]
    end
    

Log in to reply
 

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