如果可以将 str1 的一部分重新排列为 str2,如何编写返回 true 的函数? [英] How to write a function that returns true if a portion of str1 can be rearranged to str2?

查看:51
本文介绍了如果可以将 str1 的一部分重新排列为 str2,如何编写返回 true 的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在回答以下问题时遇到问题.我基本上必须编写一个代码/函数,如果可以将 str1 的一部分重新排列为 str2,则返回 true.

I am having trouble with below question. I basically have to write a code/function that returns true if a portion of str1 can be rearraged to str2.

编写函数 scramble(str1,str2),如果 str1 的一部分字符可以重新排列以匹配 str2,则返回 true,否则返回 false.

Write function scramble(str1,str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

例如:str1 是 'rkqodlw' 而 str2 是 'world' 输出应该返回 true.str1 是 'cedewaraaossoqqyt' 而 str2 是 'codewars' 应该返回 true.str1 是 'katas' 而 str2 是 'steak' 应该返回 false.

For example: str1 is 'rkqodlw' and str2 is 'world' the output should return true. str1 is 'cedewaraaossoqqyt' and str2 is 'codewars' should return true. str1 is 'katas' and str2 is 'steak' should return false.

仅使用小写字母 (a-z).将不包含标点符号或数字.需要考虑性能.

Only lower case letters will be used (a-z). No punctuation or digits will be included. Performance needs to be considered.

以下是我目前的代码:

function scramble(str1, str2) {
  var first; //longer string
  var second; //shorter string

  if(str1 || str2 === "undefined") {
    return false;
  }

  if(str1.length > str2.length) {
    first = str1;
    second = str2
  } else if(str2.length > str1.length) {
    first = str2;
    second = str1;
  }

  for (i=0; i<second.length; i++) {
    if (first.indexOf(second[i]) === -1) {
      return false;
    }
  }

  return true;

}

你能帮我解决这个问题吗?

Could you please help me with this question?

推荐答案

您可以使用带有字母计数的哈希表,并检查计数并减少计数.

You could use a hash table with the count of the letters and check with count and decrement the count.

这个提议不会改变数组.

This proposal does not mutate the arrays.

function scramble(str1, str2) {
    var count = Object.create(null);

    Array.prototype.forEach.call(str1, function(a) {
        count[a] = (count[a] || 0) + 1;
    });

    return Array.prototype.every.call(str2, function(a) {
        return count[a]--;
    });
}

console.log(scramble('rkqodlw', 'world'));              // true
console.log(scramble('cedewaraaossoqqyt', 'codewars')); // true
console.log(scramble('katas', 'steak'));                // false
console.log(scramble('', 'o'));                // false

这篇关于如果可以将 str1 的一部分重新排列为 str2,如何编写返回 true 的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆