Skip to content

Commit 4938547

Browse files
committed
solve problem 22
1 parent 6073d7f commit 4938547

File tree

1 file changed

+72
-1
lines changed

1 file changed

+72
-1
lines changed

first50.py

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,6 @@ def test_12():
643643
assert totalWaysToClimb(10, [1, 3, 5]) == 47
644644

645645

646-
test_12()
647646
"""
648647
question 13
649648
Given an integer k and a string s, find the length of the longest substring
@@ -1201,6 +1200,78 @@ def test_21():
12011200
assert getMinNumberOfRooms(intervals) == 4
12021201

12031202

1203+
"""
1204+
question 22
1205+
Given a dictionary of words and a string made up of those words (no spaces),
1206+
return the original sentence in a list. If there is more than one possible
1207+
reconstruction, return any of them. If there is no possible reconstruction,
1208+
then return null.
1209+
1210+
For example, given the set of words 'quick', 'brown', 'the', 'fox', and the
1211+
string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox'].
1212+
1213+
Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string
1214+
"bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or
1215+
['bedbath', 'and', 'beyond'].
1216+
-------------------
1217+
1218+
1. Recursion with backtracking
1219+
Recursion funtion f(index, words). Starting from the index point,
1220+
try to match words in the dictionary. It can have 0 to * matches.
1221+
Do depth-first traversal. If we can reach to the end of the string,
1222+
one solution is found. If there is no word match at some index,
1223+
we need to backtrack to try other paths.
1224+
This approach has exponential time complexity.
1225+
1226+
2. recursion with memo.
1227+
With the #1 approach, we might reach to the same index multiple times. Use a cache
1228+
to memorize the results to reduce duplicated computations.
1229+
time O(nm), n is the length of the string, m is the size of the dictionary.
1230+
space O(n) since the recursive depth is O(n).
1231+
1232+
3. BFS traversal
1233+
Use a queue to store to-be-traveled index. Intial value is [0].
1234+
Use a visited array to ensure every index only travel once.
1235+
time O(nm), space O(n)
1236+
"""
1237+
1238+
1239+
def getOriginalWords(s: str, dictionary: List[str]) -> List[str]:
1240+
# queue store the list of index along the way
1241+
queue = deque()
1242+
queue.append([0])
1243+
visited = [0] * len(s)
1244+
visited[0] = 1
1245+
while queue:
1246+
path = queue.popleft()
1247+
idx = path[-1]
1248+
for word in dictionary:
1249+
if s[idx:].startswith(word):
1250+
nextIdx = idx + len(word)
1251+
new_path = path[:]
1252+
new_path.append(nextIdx)
1253+
if nextIdx == len(s):
1254+
rtn_words = []
1255+
for i in range(1, len(new_path)):
1256+
rtn_words.append(s[new_path[i - 1] : new_path[i]])
1257+
return rtn_words
1258+
if visited[nextIdx]:
1259+
continue
1260+
visited[nextIdx] = 1
1261+
queue.append(new_path)
1262+
# no valid path
1263+
return None
1264+
1265+
1266+
def test_22():
1267+
s = "thequickbrownfox"
1268+
words = ["quick", "brown", "the", "fox"]
1269+
assert getOriginalWords(s, words) == ["the", "quick", "brown", "fox"]
1270+
s = "bedbathandbeyond"
1271+
words = ["bed", "bath", "bedbath", "and", "beyond"]
1272+
assert getOriginalWords(s, words) == ["bedbath", "and", "beyond"]
1273+
1274+
12041275
"""
12051276
question 32 TODO
12061277
This problem was asked by Jane Street.

0 commit comments

Comments
 (0)