How can I compare two shuffled strings?

后端 未结 5 967
盖世英雄少女心
盖世英雄少女心 2021-02-02 08:05

I have the following two strings:

var str1 = \"hello\";
var str2 = \"ehlol\";

How can I check whether both strings contain the same characters?

5条回答
  •  后悔当初
    2021-02-02 08:41

    May not be very optimal, but you can simply do

    str1.split("").sort().join() == str2.split("").sort().join(); //outputs true
    

    Another suggested approach in one the comments (for optimization in case string length is quite big)

    str1.length===str2.length && str1.split("").sort().join() == str2.split("").sort().join(); //first check the length to quickly rule out in case of obvious non-matches
    

提交回复
热议问题