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

LeetCode 234 - Palindrome Linked List (Easy)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 234๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ฃผ์–ด์ง„ ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ๊ฐ€ ํŒฐ๋ฆฐ๋“œ๋กฌ ์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(N) ์ด๋ฉด์„œ ๊ณต๊ฐ„ ๋ณต์žก๋„๊ฐ€ O(1) ์œผ๋กœ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด์„œ ์žฌ๊ท€ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.
์ด๋ฅผ ์œ„ํ•ด ๋จผ์ € ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด๋ฅผ ๊ตฌํ•œ ๋‹ค์Œ, ์ค‘์•™ ์œ„์น˜๊นŒ์ง€ ์ด๋™ํ•ด์„œ ํŒฐ๋ฆฐ๋“œ๋กฌ ์œ ๋ฌด๋ฅผ ํŒ๋‹จํ•ฉ๋‹ˆ๋‹ค.
์ด๋Š” a[i] ~ a[j] ๊นŒ์ง€์˜ ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ๊ฐ€ ํŒฐ๋ฆฐ๋“œ๋กฌ์ด๊ธฐ ์œ„ํ•ด์„œ๋Š”
a[i+1] ~ a[j-1] ๊นŒ์ง€๊ฐ€ ํŒฐ๋ฆฐ๋“œ๋กฌ์ด๊ณ  a[i] == a[j] ์ด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

๊ทธ๋Ÿฌ๋ฏ€๋กœ ๊ฐ๊ฐ์˜ ์žฌ๊ท€ ํ˜ธ์ถœ ๊ณผ์ •์—์„œ ๋ฐ˜ํ™˜๊ฐ’์œผ๋กœ ํŒฐ๋ฆฐ๋“œ๋กฌ ์œ ๋ฌด ์™€ tail ๋…ธ๋“œ ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์„œ
์žฌ๊ท€ ํ˜ธ์ถœ ๊ณผ์ •์—์„œ ๊ฐ๊ฐ์˜ ์„œ๋ธŒ ๋ฆฌ์ŠคํŠธ์˜ ์–‘ ๋ ๋…ธ๋“œ๋ฅผ ๋น„๊ตํ•ด์ค๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function (head) {
  const len = getLength(head);
  let half = len % 2 ? Math.floor(len / 2) : Math.floor(len / 2) - 1;

  if (len === 0) return true;

  const [answer] = dfs(len % 2 === 0, half, head, 0);
  return answer;
};

function dfs(even, pivot, head, depth) {
  if (depth === pivot) {
    if (even) return [head.val === head.next.val, head.next.next];
    else return [true, head.next];
  }

  const [subCheck, tail] = dfs(even, pivot, head.next, depth + 1);
  return [subCheck && head.val === tail.val, tail?.next];
}

function getLength(head) {
  if (!head) return 0;
  return getLength(head.next) + 1;
}
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€