这道题定义自己custom的compare function即可,按照题目的要求来。注意用stable sort因为要保持数组log的原顺序。时间复杂度O(n * log n),代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string getId(const string& s, int& i) | |
{ | |
string id; | |
while (s[i] == ' ')++i; | |
while (s[i] != ' ')id += s[i++]; | |
while (s[i] == ' ')++i; | |
return id; | |
} | |
bool compare(const string& s1, const string& s2) | |
{ | |
int i1 = 0, i2 = 0; | |
string id1 = getId(s1, i1), id2 = getId(s2, i2); | |
string log1 = s1.substr(i1), log2 = s2.substr(i2); | |
bool isDigit1 = isdigit(s1[i1]), isDigit2 = isdigit(s2[i2]); | |
if (!isDigit1 && !isDigit2) | |
{ | |
int comp = log1.compare(log2); | |
if (!comp) | |
return s1.compare(s2) < 0; | |
else | |
return comp < 0; | |
} | |
return isDigit1 ? false : true; | |
} | |
class Solution { | |
public: | |
vector<string> reorderLogFiles(vector<string>& logs) { | |
stable_sort(logs.begin(), logs.end(), compare); | |
return logs; | |
} | |
}; |
No comments:
Post a Comment