Skip to content

Commit 05355b2

Browse files
author
shangchun
committed
leetcode
1 parent a52440f commit 05355b2

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

palindrome.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# @param s, a string
2+
# @return a boolean
3+
def isPalindrome(s):
4+
head = 0
5+
tail = len(s) - 1
6+
validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
7+
while head < tail:
8+
if s[head] not in validChars:
9+
head += 1
10+
continue
11+
tailCode = ord(s[tail])
12+
if s[tail] not in validChars:
13+
tail -= 1
14+
continue
15+
if s[head].lower() == s[tail].lower():
16+
head += 1
17+
tail -= 1
18+
else:
19+
return False
20+
return True
21+
22+
23+
assert isPalindrome("A man, a plan, a canal: Panama") == True
24+
assert isPalindrome("race a car") == False
25+
assert isPalindrome("1a2") == False

removeNthFromEnd.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Definition for singly-linked list.
2+
class ListNode:
3+
def __init__(self, x):
4+
self.val = x
5+
self.next = None
6+
7+
# @return a ListNode
8+
def removeNthFromEnd(head, n):
9+
ahead = behind = head
10+
while n > 0:
11+
ahead = ahead.next
12+
n -= 1
13+
if ahead == None:
14+
node = head
15+
head = head.next
16+
node.next = None
17+
return head;
18+
while ahead.next != None:
19+
ahead = ahead.next
20+
behind = behind.next
21+
node = behind.next
22+
behind.next = node.next
23+
node.next = None
24+
return head
25+
26+
a = ListNode('a')
27+
b = ListNode('b')
28+
c = ListNode('c')
29+
d = ListNode('d')
30+
e = ListNode('e')
31+
a.next = b
32+
b.next = c
33+
c.next = d
34+
d.next = e
35+
removeNthFromEnd(a, 2)
36+
assert c.next == e
37+
38+
assert removeNthFromEnd(e, 1) == None
39+
40+
f = ListNode('f')
41+
g = ListNode('g')
42+
f.next = g
43+
assert removeNthFromEnd(f, 2) == g

0 commit comments

Comments
 (0)