返回

C++ 937:日志文件重排

后端

日志文件记录了服务器的各种事件,每条日志由两部分组成:标识符和内容。标识符是字母与数字混合的字符串,内容由空格分隔。

为了便于分析,我们需要对日志文件进行重排,使得所有内容日志(不包含标识符)按时间升序排列,而标识符日志(只包含标识符)按标识符升序排列。

解题思路

我们可以将日志文件分为两类:

  • 内容日志: 不包含标识符的日志
  • 标识符日志: 只包含标识符的日志

对内容日志,我们按内容升序排列;对标识符日志,我们按标识符升序排列。然后将两类日志合并,即可得到重排后的日志文件。

具体实现

我们可以使用以下步骤来实现日志文件重排:

  1. 将日志文件中的每条日志分割为标识符和内容。
  2. 创建两个向量:contentLogsidentifierLogs,分别用于存储内容日志和标识符日志。
  3. 对于每个日志,如果包含标识符,则将其添加到 identifierLogs;否则,将其添加到 contentLogs
  4. contentLogs 按内容升序排列,对 identifierLogs 按标识符升序排列。
  5. contentLogsidentifierLogs 合并,即可得到重排后的日志文件。

时间复杂度

此算法的时间复杂度为 O(N log N),其中 N 是日志文件中的日志条数。

代码实现

#include <algorithm>
#include <vector>
#include <string>

using namespace std;

vector<string> reorderLogFiles(vector<string>& logs) {
    vector<string> contentLogs;
    vector<string> identifierLogs;

    for (auto& log : logs) {
        if (isalpha(log[log.find(' ') + 1])) {
            contentLogs.push_back(log);
        } else {
            identifierLogs.push_back(log);
        }
    }

    sort(contentLogs.begin(), contentLogs.end(), [](const string& a, const string& b) {
        int i = a.find(' ') + 1;
        int j = b.find(' ') + 1;
        return a.substr(i) < b.substr(j);
    });

    sort(identifierLogs.begin(), identifierLogs.end());

    vector<string> result;
    result.insert(result.end(), contentLogs.begin(), contentLogs.end());
    result.insert(result.end(), identifierLogs.begin(), identifierLogs.end());

    return result;
}