公式必须使用这些文字。
Input Output
“stranger” “ngerstra”
“rotator” “torarot”
答案 0 :(得分:-1)
因此,使用此解决方案非常简单,您拥有字典,然后对字典中的每个对象稍作更改,就可以在其中基本添加一些字符串,以便如果单词为'card'
,将以这样一种方式交换字母的顺序,即当您搜索'drac'
时,card似乎是一个相似的单词。
当您搜索与词典中所用词相似的词时,为防止输出恰好是已搜索词的内容,在构造新数组时,如果索引为index,它将null
推入数组x
与搜索到的单词相同。
然后,一旦构造了数组,它将过滤掉设置为null
的所有值。
// Simple string sort function.
const sort = s => [...s].filter(x => x != null).sort().join('');
// Helper function which will state whether or not to push
// a string onto the array or push null onto the array.
const push = o => w => sort(o) === sort(w) && o != w ? o : null;
// A function that takes an array of words and a word
// via the use of currying, then magic happens!
const anagrams = d => w => d.map(o => push(o)(w)).filter(s => s != null);
// The proof is in the pudding...
const dictionary = ['stranger','ngerstra','torarot','rotator'];
const word = 'ngerstra';
const otherWord = 'rotator';
const results = anagrams(dictionary)(word);
const otherResults = anagrams(dictionary)(otherWord);
console.log(results);
console.log(otherResults);