-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay12.cpp
More file actions
63 lines (53 loc) · 1.11 KB
/
Day12.cpp
File metadata and controls
63 lines (53 loc) · 1.11 KB
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
/*
This problem was asked by Square.
Given a list of words, return the shortest unique prefix of each word. For example, given the list:
dog
cat
apple
apricot
fish
Return the list:
d
c
app
apr
f
*/
#include <bits/stdc++.h>
using namespace std;
vector<string> shortest_unique_prefix(vector<string> words)
{
unordered_map<string, int> prefix_count;
vector<string> result;
for (const string &word : words)
{
for (int i = 1; i <= word.size(); ++i)
{
string prefix = word.substr(0, i);
prefix_count[prefix]++;
}
}
for (const string &word : words)
{
for (int i = 1; i <= word.size(); ++i)
{
string prefix = word.substr(0, i);
if (prefix_count[prefix] == 1)
{
result.push_back(prefix);
break;
}
}
}
return result;
}
int main()
{
vector<string> words = {"dog", "cat", "apple", "apricot", "fish"};
vector<string> result = shortest_unique_prefix(words);
for (string s : result)
{
cout << s << endl;
}
return 0;
}