Skip to content

Commit df49457

Browse files
committed
submissions until 2019/12/24
1 parent 19a3ffe commit df49457

File tree

3 files changed

+247
-0
lines changed

3 files changed

+247
-0
lines changed

ok_add_and_search_word.py

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
"""
2+
211. Add and Search Word - Data structure design
3+
Medium
4+
5+
Design a data structure that supports the following two operations:
6+
7+
void addWord(word)
8+
bool search(word)
9+
search(word) can search a literal word or a regular expression string containing only letters a-z or `.`.
10+
A `.` means it can represent any one letter.
11+
12+
Note:
13+
You may assume that all words are consist of lowercase letters a-z.
14+
15+
Details
16+
Runtime: 276 ms, faster than 82.23% of Python3 online submissions for Add and Search Word - Data structure design.
17+
Memory Usage: 23.2 MB, less than 91.30% of Python3 online submissions for Add and Search Word - Data structure design.
18+
"""
19+
20+
21+
class WordDictionary:
22+
23+
def __init__(self):
24+
"""
25+
Initialize your data structure here.
26+
"""
27+
self.trie = {}
28+
29+
def addWord(self, word: str) -> None:
30+
"""
31+
Adds a word into the data structure.
32+
"""
33+
node = self.trie
34+
for ch in word:
35+
if ch not in node:
36+
node[ch] = {}
37+
node = node[ch]
38+
node['#'] = None
39+
40+
def search(self, word: str) -> bool:
41+
"""
42+
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
43+
"""
44+
node = self.trie
45+
return self.__search_dfs(word, 0, node) is True
46+
47+
def __search_bfs(self, word: str, trie) -> bool:
48+
""" 332 - 360 ms """
49+
q = [(trie, 0)]
50+
while q:
51+
node, i = q.pop(0)
52+
53+
if i == len(word):
54+
if '#' in node:
55+
return True
56+
else:
57+
continue
58+
59+
if word[i] == '.':
60+
for k in node.keys():
61+
if k != '#':
62+
q.append((node[k], i + 1))
63+
elif word[i] in node:
64+
q.append((node[word[i]], i + 1))
65+
66+
return False
67+
68+
def __search_dfs(self, word, w_idx, trie):
69+
""" 272 ms """
70+
if w_idx == len(word):
71+
return '#' in trie
72+
73+
if word[w_idx] == '.':
74+
for k in trie:
75+
if k != '#' and self.__search_dfs(word, w_idx + 1, trie[k]):
76+
return True
77+
elif word[w_idx] in trie and self.__search_dfs(word, w_idx + 1, trie[word[w_idx]]):
78+
return True
79+
80+
81+
def _main():
82+
wd = WordDictionary()
83+
wd.addWord('bad')
84+
wd.addWord('dad')
85+
wd.addWord('mad')
86+
assert not wd.search('pad')
87+
assert wd.search('bad')
88+
assert wd.search('.ad')
89+
assert wd.search('b.d')
90+
assert wd.search('b..')
91+
assert not wd.search('b...')
92+
assert wd.search('...')
93+
assert not wd.search('.at')
94+
wd.addWord('bat')
95+
assert wd.search('.at')
96+
97+
98+
if __name__ == '__main__':
99+
_main()

ok_implement_trie.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""208. Implement Trie (Prefix Tree)
2+
Medium
3+
4+
Implement a trie with insert, search, and startsWith methods.
5+
6+
Note:
7+
You may assume that all inputs are consist of lowercase letters a-z.
8+
All inputs are guaranteed to be non-empty strings.
9+
10+
Details
11+
Runtime: 120 ms, faster than 98.95% of Python3 online submissions for Implement Trie (Prefix Tree).
12+
Memory Usage: 25.9 MB, less than 66.67% of Python3 online submissions for Implement Trie (Prefix Tree).
13+
"""
14+
15+
16+
class Trie:
17+
18+
def __init__(self):
19+
"""
20+
Initialize your data structure here.
21+
"""
22+
self.root = {}
23+
24+
def insert(self, word: str) -> None:
25+
"""
26+
Inserts a word into the trie.
27+
"""
28+
node = self.root
29+
for ch in word:
30+
if ch not in node:
31+
node[ch] = {}
32+
node = node[ch]
33+
34+
node['#'] = None
35+
36+
def search(self, word: str) -> bool:
37+
"""
38+
Returns if the word is in the trie.
39+
"""
40+
node = self.root
41+
for ch in word:
42+
if ch not in node:
43+
return False
44+
node = node[ch]
45+
return '#' in node
46+
47+
def startsWith(self, word: str) -> bool:
48+
node = self.root
49+
for ch in word:
50+
if ch not in node:
51+
return False
52+
node = node[ch]
53+
return True

ok_word_search_2.py

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
"""
2+
212. Word Search II
3+
Hard
4+
5+
Given a 2D board and a list of words from the dictionary, find all words in the board.
6+
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally
7+
or vertically neighboring. The same letter cell may not be used more than once in a word.
8+
9+
Example:
10+
Input:
11+
board = [
12+
['o','a','a','n'],
13+
['e','t','a','e'],
14+
['i','h','k','r'],
15+
['i','f','l','v']
16+
]
17+
words = ["oath","pea","eat","rain"]
18+
Output: ["eat","oath"]
19+
20+
Note:
21+
All inputs are consist of lowercase letters a-z.
22+
The values of words are distinct.
23+
"""
24+
25+
"""
26+
Naive approach:
27+
1. Build Trie
28+
2. iter over row, col
29+
2.1. use dfs to find word
30+
31+
Details
32+
Runtime: 292 ms, faster than 80.15% of Python3 online submissions for Word Search II.
33+
Memory Usage: 27.1 MB, less than 100.00% of Python3 online submissions for Word Search II.
34+
"""
35+
from typing import List
36+
37+
38+
class Solution:
39+
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
40+
trie = {}
41+
42+
for word in words:
43+
node = trie
44+
for ch in word:
45+
if ch not in node:
46+
node[ch] = {}
47+
node = node[ch]
48+
node['#'] = None
49+
50+
n, m = len(board), len(board[0])
51+
result = set()
52+
53+
def dfs_search(i, j, node, path):
54+
if not (0 <= i < n and 0 <= j < m) or board[i][j] == '*' or board[i][j] not in node:
55+
return
56+
57+
ch = board[i][j]
58+
board[i][j] = '*'
59+
path.append(ch)
60+
61+
if '#' in node[ch]:
62+
result.add(''.join(path))
63+
64+
dfs_search(i - 1, j, node[ch], path)
65+
dfs_search(i + 1, j, node[ch], path)
66+
dfs_search(i, j - 1, node[ch], path)
67+
dfs_search(i, j + 1, node[ch], path)
68+
69+
path.pop()
70+
board[i][j] = ch
71+
72+
for i in range(n):
73+
for j in range(m):
74+
dfs_search(i, j, trie, [])
75+
76+
return list(result)
77+
78+
79+
def _main():
80+
board = [
81+
['o', 'a', 'a', 'n'],
82+
['e', 't', 'a', 'e'],
83+
['i', 'h', 'k', 'r'],
84+
['i', 'f', 'l', 'v']
85+
]
86+
words = ["oath", "pea", "eat", "rain"]
87+
assert {"eat", "oath"} == set(Solution().findWords(board, words))
88+
89+
board = [["a", "a"]]
90+
words = ["a"]
91+
assert ['a'] == Solution().findWords(board, words)
92+
93+
94+
if __name__ == '__main__':
95+
_main()

0 commit comments

Comments
 (0)