当我破解leet代码任务时,我遇到了一些.sort function的意外行为,所以我无法完成任务,直到我自己实现了插入排序函数,该函数帮助我正确地对字符数组进行排序.
所以问题是: 为什么这个函数不能与所有数组成员进行比较?
function customSortString(order: string, s: string): string {
const map={};
for(let i=0;i<order.length;i++){
map[order[i]]=i;
}
const newStr=[...s].sort((a,b)=>{
if(map[a]===undefined || map[b]===undefined || a===b){
return 0;
}
if(map[a]<map[b]){
return -1;
}
return 1;
})
return newStr.join('');
};
如果我打电话给
customSortString("exv","xwvee")
它将返回"xwev",但应返回"eexvw"
here is a description of the problem
如果我将console.log放入到排序函数中
w x
v w
e v
e w
e v
e e
e v
所以我明白了,"x"和"e"是不同的.但如果进行了比较,它将返回1,并首先显示"e",然后显示"x".
我希望我已经解释清楚了,但如果你没有解释清楚,请提出问题