class Solution { public: static bool compare(string s1,string s2){ string s1_back = s1.substr(s1.find(' ')); string s2_back = s2.substr(s2.find(' ')); return s1_back == s2_back ? s1 < s2 : s1_back < s2_back; } vector<string> reorderLogFiles(vector<string>& logs) { vector<string> letters; vector<string> digits; for(int i = 0; i < logs.size(); i++) { string c = logs[i]; if(c[c.length()-1] >= '0' && c[c.length()-1] <= '9') digits.push_back(c); else letters.push_back(c); } sort(letters.begin(), letters.end(), compare); for(int i = 0; i < letters.size(); i++) { logs[i] = letters[i]; } for(int i = letters.size(); i < letters.size()+digits.size(); i++) { logs[i] = digits[i-letters.size()]; } return logs; } };
class Solution { public: vector<string> reorderLogFiles(vector<string>& logs) { // We can break this problem into two tasks: 1) Parition 2) Sort letter-logs // Partition: letter-logs at the front, digit-logs at the back. // We're using stable_partition instead of partition to retain the original order. // stable_partition returns an iterator to the first element of the second group. auto it = stable_partition(logs.begin(), logs.end(), [](const string& str) { return isalpha(str[str.find(' ') + 1]); }); // Sort letter-logs: We're only iterating on letter-logs in this case. // We're creating a substring for every element we compare that doesn't include the identifier // If the logs are the same except the identifier, we compare the strings, otherwise, the substrings sort(logs.begin(), it, [](const string& str1, const string& str2) { auto substr1 = string(str1.begin() + str1.find(' '), str1.end()); auto substr2 = string(str2.begin() + str2.find(' '), str2.end()); return (substr1 == substr2) ? str1 < str2 : substr1 < substr2; }); return logs; } };