๋ฌธ์
ํ์ด ๊ณผ์
๊ฐ์ฅ ๊ธด ํฐ๋ฆฐ๋๋กฌ์ ๊ตฌํ๋ ๋ฌธ์ ์
๋๋ค.
๋ง์ฝ 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 |
๐ฌ ๋๊ธ