iT邦幫忙

2021 iThome 鐵人賽

DAY 12
0
自我挑戰組

30天刷題大挑戰系列 第 12

第 11 天 邁向下個階段努力( leetcode 005 )

JavaScript 解答

var longestPalindrome = function (s) {
    var a = new Date();
    var n = s.length;
    var res = '';
    var dp = [];
    while (dp.push(new Array(n).fill(-1)) < n);
    // console.log(dp);

    for (var i = n - 1; i >= 0; i--) {
        for (var j = i; j < n; j++) {
            dp[i][j] = s[i] === s[j] && ((j - i < 3) || dp[i + 1][j - 1]);
            if (dp[i][j] === undefined) {
                console.log(i, j, s[i], s[j], dp[i + 1][j - 1])
            }
            if (dp[i][j]) {
                var tmp = s.substring(i, j + 1);
                if (tmp.length > res.length) res = tmp;
            }

        }
    }
    // console.log(dp);
    console.log(new Date() - a);

    return res;
};

Ruby 解答

def expand(s, center)  
  li, ri = center.floor, center.ceil  
  if li == ri  
      li -= 1  
      ri += 1  
  end  
  left_space = li  
  right_space = s.length - ri - 1  
  max_space = [left_space, right_space].min  
  most_left = li - max_space  
  while li >= most_left do  
    if s[li] == s[ri]  
      li -= 1  
      ri += 1  
    else  
      break  
    end  
  end  
  [ri - li - 1, li + 1, ri - 1]  
end  
  
def longest_palindrome(s)  
  i = 0  
  max_si, max_ei, max_len = nil, nil, 0  
  while i <= s.length - 1 do  
    len, si, ei = expand(s, i)  
    if max_len < len  
        max_si, max_ei, max_len = si, ei, len  
    end  
    i += 0.5  
  end  
  s[max_si..max_ei]
end

上一篇
第 10 天 階段達成繼續奮鬥( leetcode 003 )
下一篇
第 12 天 小有成果保持練習( leetcode 043 )
系列文
30天刷題大挑戰16

尚未有邦友留言

立即登入留言