Skip to content

Commit 07e6ec5

Browse files
committed
Palindrome Linked List/ Valid Anagram
1 parent e31112a commit 07e6ec5

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

234 Palindrome Linked List.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
'''
2+
Given a singly linked list, determine if it is a palindrome.
3+
4+
Follow up:
5+
Could you do it in O(n) time and O(1) space?
6+
'''
7+
8+
# Definition for singly-linked list.
9+
class ListNode(object):
10+
def __init__(self, x):
11+
self.val = x
12+
self.next = None
13+
14+
15+
class Solution(object):
16+
def isPalindrome(self, head):
17+
"""
18+
:type head: ListNode
19+
:rtype: bool
20+
"""
21+
# split the list into two parts, we can reverse the first part at meantime
22+
fast = slow = head
23+
reverse = None
24+
while fast and fast.next:
25+
fast = fast.next.next
26+
reverse, reverse.next, slow = slow, reverse, slow.next
27+
# if the total number is odd, skip the centre point
28+
if fast:
29+
slow = slow.next
30+
# compare the reversed first part and normal second part
31+
while reverse:
32+
if reverse.val != slow.val:
33+
return False
34+
else:
35+
reverse = reverse.next
36+
slow = slow.next
37+
return True
38+
39+
40+
if __name__ == "__main__":
41+
n1 = ListNode(1)
42+
n2 = ListNode(2)
43+
n3 = ListNode(1)
44+
n1.next = n2
45+
n2.next = n3
46+
assert Solution().isPalindrome(n1) == True
47+
assert Solution().isPalindrome(n2) == False
48+
n1.next = n3
49+
assert Solution().isPalindrome(n1) == True

242 Valid Anagram.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'''
2+
Given two strings s and t, write a function to determine if t is an anagram of s.
3+
4+
For example,
5+
s = "anagram", t = "nagaram", return true.
6+
s = "rat", t = "car", return false.
7+
8+
Note:
9+
You may assume the string contains only lowercase alphabets.
10+
11+
Follow up:
12+
What if the inputs contain unicode characters? How would you adapt your solution to such case?
13+
'''
14+
15+
class Solution(object):
16+
def isAnagram(self, s, t):
17+
"""
18+
:type s: str
19+
:type t: str
20+
:rtype: bool
21+
"""
22+
m = {}
23+
if len(s) != len(t):
24+
return False
25+
for c in s:
26+
m[c] = m.get(c, 0) + 1
27+
for c in t:
28+
if c not in m or m[c] == 0:
29+
return False
30+
else:
31+
m[c] -= 1
32+
return True
33+
34+
35+
if __name__ == "__main__":
36+
s, t = "anagram", "nagaram"
37+
assert Solution().isAnagram(s, t) == True
38+
s, t = 'rat', 'car'
39+
assert Solution().isAnagram(s, t) == False

0 commit comments

Comments
 (0)