Skip to content

Commit 337e300

Browse files
whoisnpabranhe
authored andcommitted
added is_palindrome
1 parent ebd5e43 commit 337e300

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
def is_palindrome(head):
2+
if not head:
3+
return True
4+
fast, slow = head.next, head
5+
while fast and fast.next:
6+
fast = fast.next.next
7+
slow = slow.next
8+
second = slow.next
9+
node = None
10+
while second:
11+
nxt = second.next
12+
second.next = node
13+
node = second
14+
second = nxt
15+
while node:
16+
if node.val != head.val:
17+
return False
18+
node = node.next
19+
head = head.next
20+
return True
21+
22+
23+
def is_palindrome_stack(head):
24+
if not head or not head.next:
25+
return True
26+
27+
# Get the midpoint
28+
slow = fast = cur = head
29+
while fast and fast.next:
30+
fast, slow = fast.next.next, slow.next
31+
32+
# Push the second half into the stack
33+
stack = [slow.val]
34+
while slow.next:
35+
slow = slow.next
36+
stack.append(slow.val)
37+
38+
# Comparison
39+
while stack:
40+
if stack.pop() != cur.val:
41+
return False
42+
cur = cur.next
43+
44+
return True
45+
46+
47+
def is_palindrome_dict(head):
48+
if not head or not head.next:
49+
return True
50+
d = {}
51+
pos = 0
52+
while head:
53+
if head.val in d.keys():
54+
d[head.val].append(pos)
55+
else:
56+
d[head.val] = [pos]
57+
head = head.next
58+
pos += 1
59+
checksum = pos - 1
60+
middle = 0
61+
for v in d.values():
62+
if len(v) % 2 != 0:
63+
middle += 1
64+
else:
65+
step = 0
66+
for i in range(0, len(v)):
67+
if v[i] + v[len(v) - 1 - step] != checksum:
68+
return False
69+
step += 1
70+
if middle > 1:
71+
return False
72+
return True

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy