Skip to content

Commit 2c6190d

Browse files
committed
update trie
1 parent ea31df4 commit 2c6190d

File tree

7 files changed

+246
-48
lines changed

7 files changed

+246
-48
lines changed

README.md

Lines changed: 67 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,28 @@ List of Implementations:
77
```
88
.
99
├── array
10+
│   ├── garage.py
1011
│   ├── house_robber.py
11-
│   └── longest_increasing_subsequence.py
12-
├── builtins
13-
│   ├── dictionary.py
14-
│   ├── list.py
15-
│   ├── set.py
16-
│   └── tuple.py
17-
├── dynamic_programming
18-
│   └── max_subarray.py
12+
│   ├── longest_increasing_subsequence.py
13+
│   ├── longest_non_repeat.py
14+
│   ├── plus_one.py
15+
│   └── wiggle_sort.py
16+
├── backtrack
17+
│   ├── anagram.py
18+
│   ├── combination_sum.py
19+
│   ├── palindrome_partitioning.py
20+
│   ├── permute.py
21+
│   ├── permute_unique.py
22+
│   ├── subsets.py
23+
│   └── subsets_unique.py
24+
├── bfs
25+
│   └── shortest_distance_from_all_buildings.py
26+
├── divide-and-conquer
27+
│   ├── expression-add-operators.py
28+
│   └── the-skyline-problem.py
29+
├── dp
30+
│   ├── max_subarray.py
31+
│   └── word_break.py
1932
├── graph
2033
│   ├── find_path.py
2134
│   ├── graph.py
@@ -24,14 +37,23 @@ List of Implementations:
2437
│   └── hashtable.py
2538
├── linkedlist
2639
│   ├── first_cyclic_node.py
40+
│   ├── is_palindrome.py
2741
│   ├── kth_to_last.py
2842
│   ├── linkedlist.py
2943
│   └── remove_duplicates.py
3044
├── matrix
31-
│   └── matrix_rotation.txt
32-
├── output.txt
45+
│   ├── bomb_enemy.py
46+
│   ├── matrix_rotation.txt
47+
│   └── pacific_atlantic.py
48+
├── out.txt
3349
├── queue
34-
│   └── queue.py
50+
│   ├── __init__.py
51+
│   ├── max_sliding_window.py
52+
│   ├── moving_average.py
53+
│   ├── queue.py
54+
│   ├── reconstruct_queue.py
55+
│   └── zigzagiterator.py
56+
├── README.md
3557
├── search
3658
│   ├── binary_search.py
3759
│   ├── count_elem.py
@@ -41,28 +63,49 @@ List of Implementations:
4163
│   ├── insertion_sort.py
4264
│   ├── merge_sort.py
4365
│   ├── quick_sort.py
44-
│   └── selection_sort.py
66+
│   ├── selection_sort.py
67+
│   └── sort_colors.py
4568
├── stack
4669
│   ├── __init__.py
4770
│   ├── __init__.pyc
71+
│   ├── longest_abs_path.py
72+
│   ├── __pycache__
73+
│   │   ├── __init__.cpython-35.pyc
74+
│   │   └── stack.cpython-35.pyc
4875
│   ├── stack.py
4976
│   └── stack.pyc
5077
├── string
78+
│   ├── decode_string.py
79+
│   ├── encode_decode.py
5180
│   ├── license_number.py
81+
│   ├── missing_ranges.py
82+
│   ├── rabin_karp.py
5283
│   ├── reverse_string.py
5384
│   ├── reverse_vowel.py
54-
│   └── reverse_words.py
55-
├── testStack.py
56-
└── tree
57-
├── bintree2list.py
58-
├── deepest_left.py
59-
├── invert_tree.py
60-
├── longest_abs_path.py
61-
├── max_height.py
62-
├── predecessor.py
63-
├── same_tree.py
64-
├── successor.py
65-
├── tree.py
85+
│   ├── reverse_words.py
86+
│   └── word_squares.py
87+
├── tests
88+
│   └── test_stack.py
89+
├── tree
90+
│   ├── array2bst.py
91+
│   ├── bintree2list.py
92+
│   ├── bst_closest_value.py
93+
│   ├── BSTIterator.py
94+
│   ├── deepest_left.py
95+
│   ├── invert_tree.py
96+
│   ├── is_balanced.py
97+
│   ├── is_subtree.py
98+
│   ├── is_symmetric.py
99+
│   ├── longest_consecutive.py
100+
│   ├── max_height.py
101+
│   ├── max_path_sum.py
102+
│   ├── min_height.py
103+
│   ├── predecessor.py
104+
│   ├── same_tree.py
105+
│   ├── successor.py
106+
│   └── tree.py
107+
└── trie
108+
├── add_and_search.py
66109
└── trie.py
67110
68111

bfs/shortest_distance_from_all_buildings.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import collections
22

3-
## do BFS from each building, and decrement all empty place for every building visit
4-
## when grid[i][j] == -b_nums, it means that grid[i][j] are already visited from all b_nums
5-
## and use dist to record distances from b_nums
3+
"""
4+
do BFS from each building, and decrement all empty place for every building visit
5+
when grid[i][j] == -b_nums, it means that grid[i][j] are already visited from all b_nums
6+
and use dist to record distances from b_nums
7+
"""
8+
69
def shortest_distance(grid):
710
if not grid or not grid[0]:
811
return -1
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Given a string that contains only digits 0-9 and a target value,
3+
return all possibilities to add binary operators (not unary) +, -, or *
4+
between the digits so they prevuate to the target value.
5+
6+
Examples:
7+
"123", 6 -> ["1+2+3", "1*2*3"]
8+
"232", 8 -> ["2*3+2", "2+3*2"]
9+
"105", 5 -> ["1*0+5","10-5"]
10+
"00", 0 -> ["0+0", "0-0", "0*0"]
11+
"3456237490", 9191 -> []
12+
"""
13+
14+
def add_operator(num, target):
15+
"""
16+
:type num: str
17+
:type target: int
18+
:rtype: List[str]
19+
"""
20+
res = []
21+
if not num: return res
22+
helper(res, "", num, target, 0, 0, 0)
23+
return res
24+
25+
def helper(res, path, num, target, pos, prev, multed):
26+
print(res, path, num, target, pos, prev, multed)
27+
if pos == len(num):
28+
if (target == prev):
29+
res.append(path)
30+
return
31+
for i in range(pos, len(num)):
32+
if i != pos and num[pos] == '0': break
33+
cur = int(num[pos:i+1])
34+
print(cur)
35+
if (pos == 0):
36+
helper(res, path + str(cur), num, target, i+1, cur, cur)
37+
else:
38+
helper(res, path + "+" + str(cur), num, target, i+1, prev + cur, cur)
39+
helper(res, path + "-" + str(cur), num, target, i+1, prev - cur, -cur)
40+
helper(res, path + "*" + str(cur), num, target, i+1, prev - multed + multed * cur, multed * cur)
41+
42+
43+
# "123", 6 -> ["1+2+3", "1*2*3"]
44+
s = "123"
45+
target = 6
46+
print(add_operator(s, target))
47+
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
A city's skyline is the outer contour of the silhouette formed by all the buildings
3+
in that city when viewed from a distance.
4+
Now suppose you are given the locations and height of all the buildings
5+
as shown on a cityscape photo (Figure A),
6+
write a program to output the skyline formed by these buildings collectively (Figure B).
7+
8+
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi],
9+
where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively,
10+
and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0.
11+
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
12+
13+
For instance, the dimensions of all buildings in Figure A are recorded as:
14+
[ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .
15+
16+
The output is a list of "key points" (red dots in Figure B) in the format of
17+
[ [x1,y1], [x2, y2], [x3, y3], ... ]
18+
that uniquely defines a skyline.
19+
A key point is the left endpoint of a horizontal line segment. Note that the last key point,
20+
where the rightmost building ends,
21+
is merely used to mark the termination of the skyline, and always has zero height.
22+
Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.
23+
24+
For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].
25+
26+
Notes:
27+
28+
The number of buildings in any input list is guaranteed to be in the range [0, 10000].
29+
The input list is already sorted in ascending order by the left x position Li.
30+
The output list must be sorted by the x position.
31+
There must be no consecutive horizontal lines of equal height in the output skyline. For instance,
32+
[...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged
33+
into one in the final output as such: [...[2 3], [4 5], [12 7], ...]
34+
35+
"""
36+
37+
import heapq
38+
39+
def get_skyline(LRH):
40+
"""
41+
Wortst Time Complexity: O(NlogN)
42+
:type buildings: List[List[int]]
43+
:rtype: List[List[int]]
44+
"""
45+
skyline, live = [], []
46+
i, n = 0, len(LRH)
47+
while i < n or live:
48+
if not live or i < n and LRH[i][0] <= -live[0][1]:
49+
x = LRH[i][0]
50+
while i < n and LRH[i][0] == x:
51+
heapq.heappush(live, (-LRH[i][2], -LRH[i][1]))
52+
i += 1
53+
else:
54+
x = -live[0][1]
55+
while live and -live[0][1] <= x:
56+
heapq.heappop(live)
57+
height = len(live) and -live[0][0]
58+
if not skyline or height != skyline[-1][1]:
59+
skyline += [x, height],
60+
return skyline
61+
62+
buildings = [ [2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8] ]
63+
# [ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]
64+
print(get_skyline(buildings))
65+
66+

hashtable/hashtable.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
# MAP Abstract Data Type
2-
# Map() Create a new, empty map. It returns an empty map collection.
3-
# put(key,val) Add a new key-value pair to the map. If the key is already in the map then replace the old value with the new value.
4-
# get(key) Given a key, return the value stored in the map or None otherwise.
5-
# del Delete the key-value pair from the map using a statement of the form del map[key].
6-
# len() Return the number of key-value pairs stored in the map.
7-
# in Return True for a statement of the form key in map, if the given key is in the map, False otherwise.
8-
1+
"""
2+
MAP Abstract Data Type
3+
Map() Create a new, empty map. It returns an empty map collection.
4+
put(key,val) Add a new key-value pair to the map. If the key is already in the map then replace the old value with the new value.
5+
get(key) Given a key, return the value stored in the map or None otherwise.
6+
del Delete the key-value pair from the map using a statement of the form del map[key].
7+
len() Return the number of key-value pairs stored in the map.
8+
in Return True for a statement of the form key in map, if the given key is in the map, False otherwise.
9+
"""
910
class HashTable(object):
1011
def __init__(self, size = 11):
1112
self.size = size

tree/trie.py renamed to trie/add_and_search.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
1-
# We are asked to design an efficient data structure
2-
# that allows us to add and search for words.
3-
# The search can be a literal word or regular expression
4-
# containing “.”, where “.” can be any letter.
5-
6-
# Example:
7-
# addWord(“bad”)
8-
# addWord(“dad”)
9-
# addWord(“mad”)
10-
# search(“pad”) -> false
11-
# search(“bad”) -> true
12-
# search(“.ad”) -> true
13-
# search(“b..”) -> true
1+
"""
2+
We are asked to design an efficient data structure
3+
that allows us to add and search for words.
4+
The search can be a literal word or regular expression
5+
containing “.”, where “.” can be any letter.
146
7+
Example:
8+
addWord(“bad”)
9+
addWord(“dad”)
10+
addWord(“mad”)
11+
search(“pad”) -> false
12+
search(“bad”) -> true
13+
search(“.ad”) -> true
14+
search(“b..”) -> true
15+
"""
1516

1617
class TrieNode(object):
1718
def __init__(self, letter, isTerminal=False):

trie/trie.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Implement a trie with insert, search, and startsWith methods.
3+
4+
Note:
5+
You may assume that all inputs are consist of lowercase letters a-z.
6+
"""
7+
class TrieNode:
8+
def __init__(self):
9+
self.children = collections.defaultdict(TrieNode)
10+
self.is_word = False
11+
12+
class Trie:
13+
def __init__(self):
14+
self.root = TrieNode()
15+
16+
def insert(self, word):
17+
current = self.root
18+
for letter in word:
19+
current = current.children[letter]
20+
current.is_word = True
21+
22+
def search(self, word):
23+
current = self.root
24+
for letter in word:
25+
current = current.children.get(letter)
26+
if current is None:
27+
return False
28+
return current.is_word
29+
30+
def startsWith(self, prefix):
31+
current = self.root
32+
for letter in prefix:
33+
current = current.children.get(letter)
34+
if current is None:
35+
return False
36+
return True
37+

0 commit comments

Comments
 (0)