如何比较两个洗牌的字符串?

时间:2022-11-16 12:06:08

I have the following two strings:

我有以下两个字符串:

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

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

如何检查两个字符串是否包含相同的字符?

6 个解决方案

#1


38  

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

#2


4  

One of the recommended ways to do it is using a hash table: count how many times each character appears. Note that this works best if your characters are ASCII.

建议的方法之一是使用哈希表:计算每个字符出现的次数。请注意,如果您的字符是ASCII,则效果最佳。

The complexity of this algorithm is O(M+N+sigma) where M, N are the lengths of the strings and sigma is the number of distinct letters. The complexity of the accepted solution is higher because of the sorting, which is usually done in O(N*logN), but still a good one if your strings are short. If your strings have hundreds of thousands of characters, then this is the way to go. The drawback of using hash tables is that the memory usage is higher than the solution that uses sorting.

该算法的复杂度为O(M + N + sigma),其中M,N是字符串的长度,sigma是不同字母的数量。由于排序通常在O(N * logN)中进行排序,因此接受的解决方案的复杂性更高,但如果您的字符串很短,则仍然是一个很好的解决方案。如果你的字符串有数十万个字符,那么这就是你要走的路。使用哈希表的缺点是内存使用率高于使用排序的解决方案。

function sameLetters(str1, str2){
  var hash = {};

  var len1 = str1.length;
  var len2 = str2.length;

  // Strings with different lengths can't contain the same letters
  if(len1 !== len2) return false;

  // Count how many times each character appears in str1
  for(var i = 0; i < len1; ++i) {
    var c =  str1[i];
    if(typeof hash[c] !== 'undefined') hash[c]++;
    else hash[c] = 1;
  }

  // Make sure each character appearing in str2 was found in str1
  for(var i = 0; i < len2; ++i) {
    var c =  str2[i];
    if(typeof hash[c] === 'undefined') return false;
    if(hash[c] === 0) return false;
    hash[c]--;
  }

  // Make sure no letters are left
  for(var c in hash) {
    if(hash[c]) return false;
  }    

  return true;
}

You can then call the function like this (play with it in the browser console):

然后,您可以像这样调用该函数(在浏览器控制台中使用它):

sameLetters("hello", "ehlol"); // true
sameLetters("hello", "ehllol"); // false

#3


3  

You can use a function for this purpose like sameChars function here-

您可以在此处使用一个函数,例如sameChars函数 -

function myFunction()
{
    var input_1 = document.getElementById('input_1').value;
    var input_2 = document.getElementById('input_2').value;
    var result = sameChars(input_1,input_2);
    document.getElementById("demo").innerHTML = result;
}

function sameChars(firstStr, secondStr)
{
    var first = firstStr.split('').sort().join('');
    var second = secondStr.split('').sort().join('');
    return first.localeCompare(second)==0;
}
<input type="text" maxlength="512" id="input_1"/>
<input type="text" maxlength="512" id="input_2"/>
<button onclick="myFunction()">Check If Shuffled</button>
<p id="demo"></p>

#4


1  

Here's a modified version of Gurvinders answer.

这是Gurvinders答案的修改版本。

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

// Add sort on prototype of String object
String.prototype.sort = function () {
    return this.split('').sort().join('');
};

// First check if length of both is same
var same = str1.length === str2.length && str1.sort() === str2.sort();
console.log('Strings are same?', same);

#5


0  

You could possibly say this:

你可以这样说:

(a.length === b.length) &&   (a.split('').every(function(val) { return b.indexOf(val) > -1}))

And, in ES6 you could make it look as follows:

而且,在ES6中你可以看起来如下:

(a.length === b.length) && a.split('').every(val => { return b.indexOf(val) > -1 })

#6


0  

You can check by using simple foreach Loop. Iterate through loop (array of String) and check each elements of second String inside array of first String.

您可以使用简单的foreach循环进行检查。迭代循环(String数组)并检查第一个String数组中第二个String的每个元素。

var str1 = "hello";
var str2 = "ehlol";
var array1 = str1 .split("") ;
var array2= str2 .split("");
var isMatched = true;
if(array1.length == array2.length ){
array2.forEach(function(elem , i){
  if(array1.indexOf(elem) <0){
   isMatched = false;
   return false;
  }
})
}
if(!isMatched){
 console.log("Not Matched");
}else{
 console.log("Matched");
}

#1


38  

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

#2


4  

One of the recommended ways to do it is using a hash table: count how many times each character appears. Note that this works best if your characters are ASCII.

建议的方法之一是使用哈希表:计算每个字符出现的次数。请注意,如果您的字符是ASCII,则效果最佳。

The complexity of this algorithm is O(M+N+sigma) where M, N are the lengths of the strings and sigma is the number of distinct letters. The complexity of the accepted solution is higher because of the sorting, which is usually done in O(N*logN), but still a good one if your strings are short. If your strings have hundreds of thousands of characters, then this is the way to go. The drawback of using hash tables is that the memory usage is higher than the solution that uses sorting.

该算法的复杂度为O(M + N + sigma),其中M,N是字符串的长度,sigma是不同字母的数量。由于排序通常在O(N * logN)中进行排序,因此接受的解决方案的复杂性更高,但如果您的字符串很短,则仍然是一个很好的解决方案。如果你的字符串有数十万个字符,那么这就是你要走的路。使用哈希表的缺点是内存使用率高于使用排序的解决方案。

function sameLetters(str1, str2){
  var hash = {};

  var len1 = str1.length;
  var len2 = str2.length;

  // Strings with different lengths can't contain the same letters
  if(len1 !== len2) return false;

  // Count how many times each character appears in str1
  for(var i = 0; i < len1; ++i) {
    var c =  str1[i];
    if(typeof hash[c] !== 'undefined') hash[c]++;
    else hash[c] = 1;
  }

  // Make sure each character appearing in str2 was found in str1
  for(var i = 0; i < len2; ++i) {
    var c =  str2[i];
    if(typeof hash[c] === 'undefined') return false;
    if(hash[c] === 0) return false;
    hash[c]--;
  }

  // Make sure no letters are left
  for(var c in hash) {
    if(hash[c]) return false;
  }    

  return true;
}

You can then call the function like this (play with it in the browser console):

然后,您可以像这样调用该函数(在浏览器控制台中使用它):

sameLetters("hello", "ehlol"); // true
sameLetters("hello", "ehllol"); // false

#3


3  

You can use a function for this purpose like sameChars function here-

您可以在此处使用一个函数,例如sameChars函数 -

function myFunction()
{
    var input_1 = document.getElementById('input_1').value;
    var input_2 = document.getElementById('input_2').value;
    var result = sameChars(input_1,input_2);
    document.getElementById("demo").innerHTML = result;
}

function sameChars(firstStr, secondStr)
{
    var first = firstStr.split('').sort().join('');
    var second = secondStr.split('').sort().join('');
    return first.localeCompare(second)==0;
}
<input type="text" maxlength="512" id="input_1"/>
<input type="text" maxlength="512" id="input_2"/>
<button onclick="myFunction()">Check If Shuffled</button>
<p id="demo"></p>

#4


1  

Here's a modified version of Gurvinders answer.

这是Gurvinders答案的修改版本。

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

// Add sort on prototype of String object
String.prototype.sort = function () {
    return this.split('').sort().join('');
};

// First check if length of both is same
var same = str1.length === str2.length && str1.sort() === str2.sort();
console.log('Strings are same?', same);

#5


0  

You could possibly say this:

你可以这样说:

(a.length === b.length) &&   (a.split('').every(function(val) { return b.indexOf(val) > -1}))

And, in ES6 you could make it look as follows:

而且,在ES6中你可以看起来如下:

(a.length === b.length) && a.split('').every(val => { return b.indexOf(val) > -1 })

#6


0  

You can check by using simple foreach Loop. Iterate through loop (array of String) and check each elements of second String inside array of first String.

您可以使用简单的foreach循环进行检查。迭代循环(String数组)并检查第一个String数组中第二个String的每个元素。

var str1 = "hello";
var str2 = "ehlol";
var array1 = str1 .split("") ;
var array2= str2 .split("");
var isMatched = true;
if(array1.length == array2.length ){
array2.forEach(function(elem , i){
  if(array1.indexOf(elem) <0){
   isMatched = false;
   return false;
  }
})
}
if(!isMatched){
 console.log("Not Matched");
}else{
 console.log("Matched");
}