连接两个(或更多)字符串,并导致相同的字符串,而不考虑顺序
我想将一些字符串连接成单个字符串。 (例如:“笔”和“苹果”->“笔苹果”)但是,无论连接它们的顺序如何,我都希望输出字符串相同。
每个字符串包含非Unicode字符。
如果执行newConcat("Pen", "Apple")
,则输出"PenApple"
然后newConcat("Pen", "Apple") === newConcat("", "PenApple")
同样,newConcat("Pen", "Apple") === newConcat("", "ApplePen")
然后newConcat("Pen", "Apple")
必须输出"ApplePen"
通常,这些测试用例也必须是真实的:
newConcat("Pen", "Apple") === newConcat("Apple", "Pen"); // true
newConcat("Pen", "Apple") === newConcat("_P3n", "_App13"); // false
newConcat("Pen", "Pineapple", "Apple", "Pen") === newConcat("Apple", "Pen", "Pen", "Pineapple"); // true
到目前为止,我想出的是将字符串放入数组中,对其进行排序,然后将其返回为字符串。
function newConcat( ...strings ) {
const newArray = []
newArray.push(...strings)
return newArray.sort().join("")
}
我想知道是否有比在数组中对字符串排序更好的方法。如果我想控制将它们放在一起的顺序怎么办。
回答如下:我将结果作为数组传递,并在返回结果之前对其进行排序。我希望这会有所帮助!
连接两个(或更多)字符串,并导致相同的字符串,而不考虑顺序
我想将一些字符串连接成单个字符串。 (例如:“笔”和“苹果”->“笔苹果”)但是,无论连接它们的顺序如何,我都希望输出字符串相同。
每个字符串包含非Unicode字符。
如果执行newConcat("Pen", "Apple")
,则输出"PenApple"
然后newConcat("Pen", "Apple") === newConcat("", "PenApple")
同样,newConcat("Pen", "Apple") === newConcat("", "ApplePen")
然后newConcat("Pen", "Apple")
必须输出"ApplePen"
通常,这些测试用例也必须是真实的:
newConcat("Pen", "Apple") === newConcat("Apple", "Pen"); // true
newConcat("Pen", "Apple") === newConcat("_P3n", "_App13"); // false
newConcat("Pen", "Pineapple", "Apple", "Pen") === newConcat("Apple", "Pen", "Pen", "Pineapple"); // true
到目前为止,我想出的是将字符串放入数组中,对其进行排序,然后将其返回为字符串。
function newConcat( ...strings ) {
const newArray = []
newArray.push(...strings)
return newArray.sort().join("")
}
我想知道是否有比在数组中对字符串排序更好的方法。如果我想控制将它们放在一起的顺序怎么办。
回答如下:我将结果作为数组传递,并在返回结果之前对其进行排序。我希望这会有所帮助!