Skip to content

Commit 0d63753

Browse files
committed
Time: 18 ms (27.88%), Space: 90.5 MB (5.31%) - LeetHub
1 parent 30f089d commit 0d63753

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
function isPalindrome(head: ListNode | null): boolean {
14+
let left: ListNode | null = head;
15+
16+
function dfs(right: ListNode | null): boolean {
17+
if (!right) return true;
18+
19+
// 끝까지 내려가기
20+
if (!dfs(right.next)) return false;
21+
22+
// 돌아오면서 비교
23+
// 재귀 패턴: if (!recursiveCall()) return false;
24+
// 실패하면 false들고 위로 올라감
25+
if (left.val !== right.val) return false;
26+
27+
// 왼쪽 포인터 이동
28+
left = left.next;
29+
30+
return true;
31+
}
32+
33+
return dfs(head);
34+
}

0 commit comments

Comments
 (0)