Skip to content

Commit ea31df4

Browse files
committed
add some more
1 parent 3ce776a commit ea31df4

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

dp/word_break.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def word_break(s, word_dict):
2+
"""
3+
:type s: str
4+
:type word_dict: Set[str]
5+
:rtype: bool
6+
"""
7+
f = [False] * (len(s)+1)
8+
f[0] = True
9+
for i in range(1, len(s)+1):
10+
for j in range(0, i):
11+
if f[j] and s[j:i] in word_dict:
12+
f[i] = True
13+
break
14+
return f[-1]
15+
16+
s = "keonkim"
17+
dic = ["keon", "kim"]
18+
19+
print(word_break(s, dic))

linkedlist/is_palindrome.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
def is_palindrome(head):
2+
if not head:
3+
return True
4+
# split the list to two parts
5+
fast, slow = head.next, head
6+
while fast and fast.next:
7+
fast = fast.next.next
8+
slow = slow.next
9+
second = slow.next
10+
slow.next = None # Don't forget here! But forget still works!
11+
# reverse the second part
12+
node = None
13+
while second:
14+
nxt = second.next
15+
second.next = node
16+
node = second
17+
second = nxt
18+
# compare two parts
19+
# second part has the same or one less node
20+
while node:
21+
if node.val != head.val:
22+
return False
23+
node = node.next
24+
head = head.next
25+
return True
26+
27+
def is_palindrome_stack(head):
28+
if not head or not head.next:
29+
return True
30+
31+
# 1. Get the midpoint (slow)
32+
slow = fast = cur = head
33+
while fast and fast.next:
34+
fast, slow = fast.next.next, slow.next
35+
36+
# 2. Push the second half into the stack
37+
stack = [slow.val]
38+
while slow.next:
39+
slow = slow.next
40+
stack.append(slow.val)
41+
42+
# 3. Comparison
43+
while stack:
44+
if stack.pop() != cur.val:
45+
return False
46+
cur = cur.next
47+
48+
return True

sorting/sort_colors.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
def sort_colors(nums):
2+
i = j = 0
3+
for k in range(len(nums)):
4+
v = nums[k]
5+
nums[k] = 2
6+
if v < 2:
7+
nums[j] = 1
8+
j += 1
9+
if v == 0:
10+
nums[i] = 0
11+
i += 1
12+
13+
nums = [0,1,1,1,2,2,2,1,1,1,0,0,0,0,1,1,1,0,0,2,2]
14+
sort_colors(nums)
15+
print(nums)

0 commit comments

Comments
 (0)