[LeetCode] Reorder Data in Log Files

937. Reorder Data in Log Files

You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.

There are two types of logs:

  • Letter-logs: All words (except the identifier) consist of lowercase English letters.
  • Digit-logs: All words (except the identifier) consist of digits.

Reorder these logs so that:

  1. The letter-logs come before all digit-logs.
  2. The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
  3. The digit-logs maintain their relative ordering.

Return the final order of the logs.

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
class Solution {
bool alldigit(string s) {
int i = 0, n = s.length();
while(i < n and s[i] != ' ') i++;
i++;
while(i < n) {
if(s[i] != ' ' and !isdigit(s[i])) return false;
i++;
}
return true;
}
public:
vector<string> reorderLogFiles(vector<string>& logs) {
vector<string> digits;
vector<pair<string, string>> letters;
for(auto& log : logs) {
if(alldigit(log)) digits.push_back(log);
else {
auto div = log.find(' ');
letters.push_back({log.substr(0,div), log.substr(div)});
}
}
sort(begin(letters), end(letters), [](auto a, auto b) {
if(a.second == b.second) return a.first < b.first;
return a.second < b.second;
});
vector<string> res;
for(auto& [id, v] : letters) res.push_back(id + v);
for(auto& d : digits) res.push_back(d);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/28/PS/LeetCode/reorder-data-in-log-files/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.