Skip to content

Commit 29f2c94

Browse files
committed
[LeetCode Sync] Runtime - 15 ms (95.28%), Memory - 39.2 MB (49.46%)
1 parent 476be73 commit 29f2c94

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword="palindrome-sequence"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg" style="width: 422px; height: 62px;" />
6+
<pre>
7+
<strong>Input:</strong> head = [1,2,2,1]
8+
<strong>Output:</strong> true
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg" style="width: 182px; height: 62px;" />
13+
<pre>
14+
<strong>Input:</strong> head = [1,2]
15+
<strong>Output:</strong> false
16+
</pre>
17+
18+
<p>&nbsp;</p>
19+
<p><strong>Constraints:</strong></p>
20+
21+
<ul>
22+
<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
23+
<li><code>0 &lt;= Node.val &lt;= 9</code></li>
24+
</ul>
25+
26+
<p>&nbsp;</p>
27+
<strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def isPalindrome(self, head: Optional[ListNode]) -> bool:
8+
# slow, fast = head, head.next
9+
# while fast and fast.next:
10+
# slow, fast = slow.next, fast.next.next
11+
# last, current = None, slow.next
12+
13+
# while current:
14+
# tmp = current.next
15+
# current.next = last
16+
# last, current = current, tmp
17+
18+
# while last:
19+
# if last.val != head.val:
20+
# return False
21+
# last, head = last.next, head.next
22+
23+
# return True
24+
25+
dummy = head
26+
nums = []
27+
while dummy:
28+
nums.append(dummy.val)
29+
dummy = dummy.next
30+
return nums == nums[::-1]

0 commit comments

Comments
 (0)