-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathLongest Word in Dictionary.cpp
61 lines (47 loc) · 1.38 KB
/
Longest Word in Dictionary.cpp
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
class Solution {
public:
struct comp{
bool operator()(string& a, string& b){
if(a.size() == b.size()){
for(int i = 0; i < a.size(); i++){
if(a[i] < b[i]){
return true;
}
else if(a[i] > b[i]){
return false;
}
}
}
return a.size() > b.size();
}
};
string getsubstr(string s){
int n = s.size();
string ans = "";
for(int i = 0; i < n-1; i++){
ans += s[i];
}
return ans;
}
string longestWord(vector<string>& words) {
map<string, bool> m;
int n = words.size();
for(int i = 0; i < n; i++){
m[words[i]] = true;
}
sort(words.begin(), words.end(), comp());
// for(int i = 0; i < n; i++){
// cout << words[i] << " ";
// }
for(int i = 0; i < n; i++){
string temp = getsubstr(words[i]);
while(temp.size() != 0 && m.find(temp) != m.end()){
temp = getsubstr(temp);
}
if(temp.size() == 0){
return words[i];
}
}
return "";
}
};