-
Notifications
You must be signed in to change notification settings - Fork 0
/
daily_coding_problem_22.test.js
67 lines (55 loc) · 1.58 KB
/
daily_coding_problem_22.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
This problem was asked by Microsoft.
Given a dictionary of words and a string made up of those words (no spaces),
return the original sentence in a list. If there is more than one possible
reconstruction, return any of them. If there is no possible reconstruction,
then return null.
For example, given the set of words 'quick', 'brown', 'the', 'fox', and the
string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox'].
Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the
string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond'] or
['bedbath', 'and', 'beyond'].
*/
const originalSentence = (dict, str) => {
if (!dict || !str) return null
const result = []
let word = ''
for (let i = 0; i < str.length; i++) {
word += str[i]
if (dict[word]) {
result.push(word)
word = ''
}
}
return result.length ? result : null
}
// TESTS ///////////////////////////////////////////////////////////////////////
test('#1', () => {
const dict = {
quick: true,
brown: true,
the: true,
fox: true
}
const str = 'thequickbrownfox'
expect(originalSentence(dict, str)).toEqual(['the', 'quick', 'brown', 'fox'])
})
test('#2', () => {
const dict = {
bed: true,
bath: true,
bedbath: true,
and: true,
beyond: true
}
const str = 'bedbathandbeyond'
expect(originalSentence(dict, str)).toEqual(['bed', 'bath', 'and', 'beyond'])
})
test('#3', () => {
const dict = {
lorem: true,
ipsum: true
}
const str = 'dolorsitamet'
expect(originalSentence(dict, str)).toBe(null)
})