public class Solution
{
public string[] ReorderLogFiles(string[] logs)
{
var list1 = new List<string>();
var list2 = new List<string>();
foreach (var log in logs)
{
var spacePosition = log.IndexOf(' ');
var c = log[spacePosition + ];
if (c >= && c <= )
{
list2.Add(log);
}
else
{
list1.Add(log);
}
}
var list = list1.OrderBy(x => x.Substring(x.IndexOf(' ') + )).ToList();
list.AddRange(list2);
return list.ToArray();
}
}
补充一份C++的实现:
bool cmp(const pair<string, string>& a, const pair<string, string>& b) {
return a.second < b.second;
}
class Solution {
public:
vector<string> reorderLogFiles(vector<string>& logs) {
map<string, string> V1;//记录文本log
vector<string> V2;//记录数字log
for (auto log : logs) {
int spacePosition = ;
for (int i = ; i < log.length(); i++) {
if (log[i] == ' ') {
spacePosition = i;//找到第一个空格的下标
break;
}
}
char c = log[spacePosition + ];//找到空格后第一个字符
if (c >= && c <= ) {//ASCII码在48~57,表示数字0~9
V2.push_back(log);//存储数字log
}
else {
//Key值是原始log,Value值是去除头部的identifier之后的内容
V1.insert(make_pair(log, log.substr(spacePosition + )));
}
}
//将map转换为vector
vector<pair<string, string>> vec(V1.begin(), V1.end()); //按照value值排序
sort(vec.begin(), vec.end(), cmp); vector<string> V;//记录最终结果
for (auto p : vec) {
V.push_back(p.first);
}
for (auto p : V2) {
V.push_back(p);
}
return V;
}
}; int main()
{
Solution S;
vector<string> V;
V.push_back("a1 9 2 3 1");
V.push_back("g1 act car");
V.push_back("zo4 4 7");
V.push_back("ab1 off key dog");
V.push_back("a8 act zoo");
vector<string> V2 = S.reorderLogFiles(V);
for (auto v : V2) {
cout << v << endl;
}
}
提交显示错误的问题,我这里没有遇到,截图如下: