1 题目
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"]
2 尝试解
2.1 分析
给定一组记录,每条记录都是由识别符和若干单词组成。一条记录中的所有单词要么全部字母,要么全部为数字。现在要对记录重新排序,将所有单词为字母的记录按照由单词组成的字符串的顺序排列,如果单词全部相同,则比较识别符。所有单词为数字的记录则保持原有相对顺序,并且放在所有单词为字母的记录之后。
使用一个数组digit和一个小顶堆letter来分别存储数字记录和字母记录。对于每一条记录log,找到识别符之后的由单词组成的字符串words,如果是数字记录,按照相对顺序存入digit末尾,如果是字母记录,则以<words,log>的形式存入letter中。最后将字母记录从letter中依序取出,再与digit合并即可。
2.2 代码
class Solution {
public:
struct cmp{
bool operator() (pair<string,string>&A, pair<string,string>&B){
if(A.first > B.first) return true;
if(A.first == B.first && A.second > B.second) return true;
return false;
}
};
vector<string> reorderLogFiles(vector<string>& logs) {
vector<string> digit;
vector<string> result;
priority_queue<pair<string,string>,vector<pair<string,string>>,cmp> letter;
for(auto log : logs){
int index = 0;
while(log[index]!=' ') index++;
string word = log.substr(index+1);
if(isdigit(word[0]))
digit.push_back(log);
else{
letter.push(make_pair(word,log));
}
}
while(!letter.empty()){
result.push_back(letter.top().second);
letter.pop();
}
result.insert(result.end(),digit.begin(),digit.end());
return result;
}
};
3 标准解
class Solution {
public:
vector<string> reorderLogFiles(vector<string>& logs) {
vector<string> digitLogs, ans;
vector<pair<string, string>> letterLogs;
for (string &s : logs) {
int i = 0;
while (s[i] != ' ') ++i;
if (isalpha(s[i + 1])) letterLogs.emplace_back(s.substr(0, i), s.substr(i + 1));
else digitLogs.push_back(s);
}
sort(letterLogs.begin(), letterLogs.end(), [&](auto& a, auto& b) {
return a.second == b.second ? a.first < b.first : a.second < b.second;
});
for (auto &p : letterLogs) ans.push_back(p.first + " " + p.second);
for (string &s : digitLogs) ans.push_back(s);
return ans;
}
};