插入一个字符串。创建新字符串,该字符串是插入的字符串在其中心附近的镜像反向

时间:2018-12-20 13:37:19

标签: javascript arrays

公式必须使用这些文字。

Input               Output

“stranger”          “ngerstra”
“rotator”           “torarot”

1 个答案:

答案 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);