-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlongest_words.cpp
More file actions
69 lines (64 loc) · 1.74 KB
/
longest_words.cpp
File metadata and controls
69 lines (64 loc) · 1.74 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
64
65
66
67
68
69
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
/**
* Describe: Given a series of words, find all words with the longest length.
* Please provide a online algorithm.
*/
class Solution {
public:
vector<string> longestWords(vector<string> &dictionary) {
vector<int> indexes(dictionary.size(), 0);
// building a flection for not moving words in the dictionary
for (size_t i = 0; i < dictionary.size(); i++) {
indexes[i] = i;
}
int pre = 0;
int cur = 0;
int idx1, idx2;
for (size_t i = 1; i < dictionary.size(); i++) {
idx1 = indexes[i];
idx2 = indexes[cur];
// split the array based on the current position
if (dictionary[idx1].length() < dictionary[idx2].length()) {
swap(indexes[i], indexes[pre]);
pre++;
cur++;
} else if (dictionary[idx1].length() == dictionary[idx2].length()) {
cur++;
} else {
cur = i;
pre = i;
}
}
vector<string> result;
// retrieve all result
while (dictionary.size() > 0 && pre <= cur) {
result.push_back(dictionary[indexes[pre]]);
pre++;
}
return result;
}
};
int main() {
Solution so;
vector<string> test;
int n;
string str;
while (cin >> n) {
test.clear();
while (n-- > 0) {
cin >> str;
test.push_back(str);
}
auto re = so.longestWords(test);
cout << "result: ";
for (auto& ele : re) {
cout << ele << " ";
}
cout << endl;
}
return 0;
}