๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 5 - Longest Palindromic Substring (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 5๋ฒˆ

ํ’€์ด ๊ณผ์ •

๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋งŒ์•ฝ dp(i, j) = i์—์„œ j๊นŒ์ง€์˜ ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ์˜ ๊ธธ์ด ๋ผ๊ณ  ์ •์˜ํ•œ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ ํ™”์‹์„ ์„ธ์šธ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

dp(i, j) = if dp[i] == dp[j] & dp(i+1, j-1) is palindrome, dp(i+1, j-1) + 2 else 0


๊ธฐ์ € ์‚ฌ๋ก€๋กœ ๊ฐ ๋ฌธ์ž๋Š” ๊ธธ์ด๊ฐ€ 1์ธ ํŒฐ๋ฆฐ๋“œ๋กฌ์ด๋ผ๋Š” ๊ฒƒ์— ์œ ์˜ํ•˜์—ฌ ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function (s) {
  let answer = "";
  const dp = new Array(s.length)
    .fill(null)
    .map((x) => new Array(s.length).fill(-1));

  for (let i = 0; i < s.length; i++) {
    dp[i][i] = 1;
    answer = s[i];
  }

  for (let len = 2; len <= s.length; len++) {
    for (let start = 0; start <= s.length - len; start++) {
      let end = start + len - 1;

      if (s[start] === s[end]) {
        if (start + 1 === end) dp[start][end] = 2;
        else if (dp[start + 1][end - 1]) {
          dp[start][end] = dp[start + 1][end - 1] + 2;
        } else {
          dp[start][end] = 0;
        }
      } else {
        dp[start][end] = 0;
      }

      if (answer.length < dp[start][end]) answer = s.slice(start, end + 1);
    }
  }

  return answer;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 79 - Word Search (Medium)  (0) 2021.03.03
LeetCode 771 - Jewels and Stones (Easy)  (0) 2021.03.03
LeetCode 206 - Reverse Linked List (Easy)  (0) 2021.03.03
LeetCode 136 - Single Number (Easy)  (0) 2021.03.03
LeetCode 104 - Maximum Depth of Binary Tree (Easy)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€