我试图将以下c ++答案(来自上面的讨论)转换为javascript。
static bool myCompare(string a, string b){
int i = a.find(' ');
int j = b.find(' ');
if(isdigit(a[i + 1]))
if(isdigit(b[j + 1]))
return false; // a b are both digit logs, a == b, keep their original order
else
return false; // a is digit log, b is letter log, a > b
else
if(isdigit(b[j + 1]))
return true; // a is letter log, b is digit log, a < b
else {
if (a.substr(i) == b.substr(j))
return a.substr(0,i) < b.substr(0,j); //If string part is the same, compare key
else
return a.substr(i) < b.substr(j); // a and b are both letter
}
}
vector<string> reorderLogFiles(vector<string>& logs) {
//The order of equal elements is guaranteed to be preserved in stable_sort.
//Use sort() cannot pass the OJ.
stable_sort(logs.begin(), logs.end(), myCompare);
return logs;
}
我的解决方案如下:
var reorderLogFiles = function(logs) {
return logs.sort(cmp);
}
var cmp = function(a, b) {
let i = a.indexOf(' ');
let j = b.indexOf(' ');
if(isdigit(a[i + 1])) {
if(isdigit(b[j + 1])) {
// a, b digit, a == b
return 0;
} else {
// a digit, b letter, b|a
return 1;
}
} else {
let condi;
// a letter, b digit, a|b
if(isdigit(b[j + 1])) {
return -1;
} else {
// both letter
if (a.substring(i+1) === b.substring(j+1)) {
// start from space, all same, compare key
condi = a.substring(0,i).localeCompare(b.substring(0,j));
//console.log('same', condi, a.substring(0,i), b.substring(0,j));
return condi;
} else {
}
}
}
我的输出与预期输出之间的差异:
"s 1088746413789"
萧十郎
相关分类