【问题标题】:Anagram of strings of arrays数组字符串的字谜
【发布时间】:2021-09-16 23:22:39
【问题描述】:

这个程序只处理一个单词,但我想传递一个字符串数组(多个单词)。

let output = getAnagrams("CATCH"); //it is working for this

let output = getAnagrams(["catch", "Priest", "Monkey", "Bruise"]); 

我希望它为此工作。

function swap(chars, i, j) {
    var tmp = chars[i];
    chars[i] = chars[j];
    chars[j] = tmp;
}
function getAnagrams(input) {
    let newInput = input.toString().toLowerCase();
    console.log(newInput);
    var counter = [],
        anagrams = [],
        chars = newInput.split(''),
        length = chars.length,
        i;

    for (i = 0; i < length; i++) {
        counter[i] = 0;
    }

    anagrams.push(newInput);
    i = 0;
    while (i < length) {
        if (counter[i] < i) {
            swap(chars, i % 2 === 1 ? Counter[i] : 0, i);
            counter[i]++;
            i = 0;
            anagrams.push(chars.join(''));
        } else {
            counter[i] = 0;
            i++;
        }
    }
    // return anagrams;
}

【问题讨论】:

  • 如果您真的尝试了很多,那么请向我们展示您的尝试。另外,请阅读How to Ask,以便您了解为什么您的问题不恰当。
  • 嘿,我尝试了循环,但这不起作用,因为我不确定我应该把它放在哪里。
  • 什么是swap - 它在您的代码中,但未包含在问题中。
  • 您的输入现在是一个字符串数组。 Loop over the array 并在每个元素上使用您的代码。
  • Jamiec 这是一个我忘了写的函数。但现在我把它放在这里。

标签: javascript arrays string anagram


【解决方案1】:

既然您已经有了一个需要 1 个字符串的方法,为什么不为数组中的每个字符串调用它,然后使用 flatMap 展平返回的数组

function getAnagrams(input) {
    let newInput = input.toString().toLowerCase();
    var counter = [],
        anagrams = [],
        chars = newInput.split(''),
        length = chars.length,
        i;

    for (i = 0; i < length; i++) {
        counter[i] = 0;
    }

    anagrams.push(newInput);
    i = 0;
    while (i < length) {
        if (counter[i] < i) {
            swap(chars, i % 2 === 1 ? counter[i] : 0, i);
            counter[i]++;
            i = 0;
            anagrams.push(chars.join(''));
        } else {
            counter[i] = 0;
            i++;
        }
    }
     return anagrams;
}

function swap(arr,i,j){
  const tmp = arr[i];
  arr[i] = arr[j]
  arr[j] = tmp
}

const result = ["catch", "Priest", "Monkey", "Bruise"].flatMap(i => getAnagrams(i))

console.log(result)

【讨论】:

    猜你喜欢
    • 2014-10-24
    • 2011-11-30
    • 2021-02-14
    • 2012-01-22
    • 2017-01-16
    • 2012-03-27
    • 1970-01-01
    • 2014-11-12
    • 2020-10-28
    相关资源
    最近更新 更多