You have an array of `logs`. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. Then, either:
- Each word after the identifier will consist only of lowercase letters, or;
- Each word after the identifier will consist only of digits.
We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after its identifier.
Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order.
Return the final order of the logs.
Example 1:
Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
Constraints:
-
0 <= logs.length <= 100
-
3 <= logs[i].length <= 100
-
is guaranteed to have an identifier, and a word after the identifier.logs[i]
這道題讓給日志排序,每條日志是由空格隔開的一些字元串,第一個字元串是辨別符,可能由字母和數字組成,後面的是日志的内容,隻有兩種形式的,要麼都是數字的,要麼都是字母的。排序的規則是對于内容是字母的日志,按照字母順序進行排序,假如内容相同,則按照辨別符的字母順序排。而對于内容的是數字的日志,放到最後面,且其順序相對于原順序保持不變。部落客感覺這道題似曾相識啊,貌似之前在很多 OA 中見過,最後還是被 LeetCode 收入囊中了。其實這道題就是個比較複雜的排序的問題,兩種日志需要分開處理,對于數字日志,不需要排序,但要記錄其原始順序。這裡就可以用一個數組專門來儲存數字日志,這樣最後加到結果 res 後面,就可以保持其原來順序。關鍵是要對字母型日志進行排序,同時還要把辨別符提取出來,這樣在周遊日志的時候,先找到第一空格的位置,這樣前面的部分就是辨別符了,後面的内容就是日志内容了,此時判斷緊跟空格位置的字元,假如是數字的話,說明目前日志是數字型的,加入數組 digitLogs 中,并繼續循環。如果不是的話,将兩部分分開,存入到一個二維數組 data 中。之後要對 data 數組進行排序,并需要重寫排序規則,要根據日志内容排序,若日志内容相等,則根據辨別符排序。最後把排序好的日志按順序合并,存入結果 res 中,最後别忘了把數字型日志也加入 res, 參見代碼如下:
class Solution {
public:
vector<string> reorderLogFiles(vector<string>& logs) {
vector<string> res, digitLogs;
vector<vector<string>> data;
for (string log : logs) {
auto pos = log.find(" ");
if (log[pos + 1] >= '0' && log[pos + 1] <= '9') {
digitLogs.push_back(log);
continue;
}
data.push_back({log.substr(0, pos), log.substr(pos + 1)});
}
sort(data.begin(), data.end(), [](vector<string>& a, vector<string>& b) {
return a[1] < b[1] || (a[1] == b[1] && a[0] < b[0]);
});
for (auto &a : data) {
res.push_back(a[0] + " " + a[1]);
}
for (string log : digitLogs) res.push_back(log);
return res;
}
};
參考資料:
https://leetcode.com/problems/reorder-data-in-log-files/
https://leetcode.com/problems/reorder-data-in-log-files/discuss/192438/C%2B%2B-O(NlogN)-Time-O(N)-Space
https://leetcode.com/problems/reorder-data-in-log-files/discuss/193656/C%2B%2B-stable_sort-easy-to-understand
https://leetcode.com/problems/reorder-data-in-log-files/discuss/193872/Java-Nothing-Fancy-15-lines-2ms-all-clear.
[LeetCode All in One 題目講解彙總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)
喜歡請點贊,疼愛請打賞❤️~.~ 微信打賞 ![]() | Venmo 打賞 |