Reorder Data in Log File
inline string getType(string log) {
return (isdigit(log.back())? "digit" : "letter");
}
inline string getMessage(string log) {
return log.substr(log.find('-'));
}
inline string getID(string log) {
return log.substr(0, log.find('-'));
}
bool comp(string log1, string log2) {
// is log1 < log2?
if(getMessage(log1) == getMessage(log2))
return getID(log1) < getID(log2);
return getMessage(log1) < getMessage(log2);
}
vector<string> Solution::reorderLogs(vector<string> &A) {
vector<string> digits;
// store digits in order
for(string x: A)
if(getType(x) == "digit")
digits.push_back(x);
int digitCount = digits.size();
int letterCount = A.size() - digitCount;
// segregate
int p1 = 0, p2 = A.size() - 1;
while(p1 < p2)
if(getType(A[p1]) == "letter")
p1++;
else if(getType(A[p2]) == "digit")
p2--;
else
swap(A[p1++], A[p2--]);
// place digit logs
int k = 0;
for(int i = letterCount; i < A.size(); i++)
A[i] = digits[k++];
// sort the letter logs
sort(A.begin(), A.begin() + letterCount, comp);
return A;
}
Store the digit logs in a separate vector to preserve their order.
Segregate the digits and letters such that letters appear before the digits.
Insert the digits back into the digits portion in order.
Create a custom comparator function according to the specified condition.
Sort the letter part.
Last updated