-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathLongestWordInDictionaryThroughDeleting.cpp
62 lines (50 loc) · 1.45 KB
/
LongestWordInDictionaryThroughDeleting.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
62
class Solution {
public:
int get(vector<int> temp, int start, int end){
int len = temp.size();
for(int i = 0; i < len; i++){
if(temp[i] > start){
return temp[i];
}
}
return end;
}
string findLongestWord(string s, vector<string>& d) {
string ans = "";
int i = 0, n = s.size();
map<char, vector<int>> m;
for(int i = 0; i < n; i++){
m[s[i]].push_back(i);
}
while(i < d.size()){
bool found = true;
int len = d[i].size(), start = -1;
for(int j = 0; j < len; j++){
char c = d[i][j];
if(m.find(c) == m.end()){
found = false;
break;
}
else{
start = get(m[c], start, n);
if(start == n){
found = false;
break;
}
}
}
if(found){
if(ans.size() < len){
ans = d[i];
}
else if(ans.size() == len){
if(ans > d[i]){
ans = d[i];
}
}
}
i++;
}
return ans;
}
};