- 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
本文深入探讨了如何通过字母和数字内容对日志进行高效排序的算法。文章详细解释了如何利用C++ STL中的字符串操作和排序功能,以及操作符重载来实现这一目标。通过具体示例,读者将理解日志按字母内容字典序排列,相同内容按ID排序,数字内容保持原序的排序逻辑。
475

被折叠的 条评论
为什么被折叠?



