- Log Sorting
Given a list of string logs, in which each element representing a log. Each log can be separated into two parts by the first space. The first part is the ID of the log, while the second part is the content of the log. (The content may contain spaces as well.) The content is composed of only letters and spaces, or only numbers and spaces.
Now you need to sort logs by following rules:
Logs whose content is letter should be ahead of logs whose content is number.
Logs whose content is letter should be sorted by their content in lexicographic order. And when two logs have same content, sort them by ID in lexicographic order.
Logs whose content is number should be in their input order.
Example
Example 1:
Input:
logs = [
“zo4 4 7”,
“a100 Act zoo”,
“a1 9 2 3 1”,
“g9 act car”
]
Output:
[
“a100 Act zoo”,
“g9 act car”,
“zo4 4 7”,
“a1 9 2 3 1”
]
Explanation: “Act zoo” < “act car”, so the output is as above.
Example 2:
Input:
logs = [
“zo4 4 7”,
“a100 Actzoo”,
“a100 Act zoo”,
“Tac Bctzoo”,
“Tab Bctzoo”,
“g9 act car”
]
Output:
[
“a100 Act zoo”,
“a100 Actzoo”,
“Tab Bctzoo”,
“Tac Bctzoo”,
“g9 act car”,
“zo4 4 7”
]
Explanation:
Because “Bctzoo” == “Bctzoo”, the comparison “Tab” and “Tac” have “Tab” < Tac “, so” Tab Bctzoo “< Tac Bctzoo”.
Because ’ '<‘z’, so “A100 Act zoo” < A100 Actzoo".
Notice
The total number of logs will not exceed 5000
The length of each log will not exceed 100
Each log’s ID is unique.
解法1:
这道题目可以重温一下c++ stl里面的
string::substr()
string::find_first_of()
sort()
和
opertor < 操作符重载
enum Type {
LETTERS,
DIGITS,
};
struct Entry {
string id;
string content;
int index;
Type tp;
friend bool operator < (const Entry &a, const Entry &b);
};
bool operator < (const Entry &a, const Entry &b) {
if ((a.tp == DIGITS) && (b.tp == DIGITS)) {
return a.index < b.index;
}
if ((a.tp == LETTERS) && (b.tp == LETTERS)) {
if (a.content == b.content) {
if (a.id == b.id) {
return a.index < b.index;
} else {
return a.id < b.id;
}
} else {
return a.content < b.content;
}
}
return a.tp < b.tp;
}
class Solution {
public:
/**
* @param logs: the logs
* @return: the log after sorting
*/
vector<string> logSort(vector<string> &logs) {
vector<string> result;
int logCount = logs.size();
vector<Entry> entries(logCount);
for (int i = 0; i < logCount; ++i) {
int pos = logs[i].find_first_of(' ');
entries[i].id = logs[i].substr(0, pos);
entries[i].content = logs[i].substr(pos + 1);
entries[i].index = i;
entries[i].tp = (entries[i].content[0] >= '0') && (entries[i].content[0] <= '9') ? DIGITS : LETTERS;
}
sort(entries.begin(), entries.end());
for (auto entry : entries) {
result.push_back(entry.id + ' ' + entry.content);
}
return result;
}
};
代码同步在
https://github.com/luqian2017/Algorithm