javascript中的字谜查找器
Posted
技术标签:
【中文标题】javascript中的字谜查找器【英文标题】:Anagrams finder in javascript 【发布时间】:2010-10-28 21:49:58 【问题描述】:我应该用 javascript 编写一个程序来查找提供的一系列单词中的所有字谜。例如:
monk, konm, nkom, bbc, cbb, dell, ledl, llde
输出应按行分类:
1. monk konm, nkom;
2. bbc cbb;
3. dell ledl, llde;
我已经按字母顺序对它们进行了排序,并将它们放入一个数组中。即:
kmno kmno bbc bbc dell dell
但是我一直在比较和查找数组中匹配的字谜。
任何帮助将不胜感激。
【问题讨论】:
【参考方案1】:这是我的看法:
var input = "monk, konm, bbc, cbb, dell, ledl";
var words = input.split(", ");
for (var i = 0; i < words.length; i++)
var word = words[i];
var alphabetical = word.split("").sort().join("");
for (var j = 0; j < words.length; j++)
if (i === j)
continue;
var other = words[j];
if (alphabetical === other.split("").sort().join(""))
console.log(word + " - " + other + " (" + i + ", " + j + ")");
输出的位置(单词、匹配项和两者的索引):
monk - konm (0, 1)
konm - monk (1, 0)
bbc - cbb (2, 3)
cbb - bbc (3, 2)
dell - ledl (4, 5)
ledl - dell (5, 4)
为了按字母顺序获取字符,我使用 split("") 获取数组,称为 sort() 并使用 join("") 从数组中获取字符串。
【讨论】:
【参考方案2】:Javascript 对象非常适合此用途,因为它们本质上是键/值存储:
// Words to match
var words = ["dell", "ledl", "abc", "cba"];
// The output object
var anagrams = ;
for (var i in words)
var word = words[i];
// sort the word like you've already described
var sorted = sortWord(word);
// If the key already exists, we just push
// the new word on the the array
if (anagrams[sorted] != null)
anagrams[sorted].push(word);
// Otherwise we create an array with the word
// and insert it into the object
else
anagrams[sorted] = [ word ];
// Output result
for (var sorted in anagrams)
var words = anagrams[sorted];
var sep = ",";
var out = "";
for (var n in words)
out += sep + words[n];
sep = "";
document.writeln(sorted + ": " + out + "<br />");
【讨论】:
您能详细说明您的代码吗?读完之后,我更加困惑。提前致谢。【参考方案3】:简单的解决方案
function anagrams(stringA, stringB)
return cleanString(stringA) === cleanString(stringB);
function cleanString(str)
return str.replace(/[^\w]/g).toLowerCase().split('').sort().join()
anagrams('monk','konm')
如果是字谜函数将返回true,否则返回false
【讨论】:
【参考方案4】:我今天解决了一个与此类似的问题,并想分享我的工作成果。我只专注于检测字谜,因此处理单词列表不是我练习的一部分,但这个算法应该提供一种高性能的方法来检测两个单词之间的字谜。
function anagram(s1, s2)
if (s1.length !== s2.length)
// not the same length, can't be anagram
return false;
if (s1 === s2)
// same string must be anagram
return true;
var c = '',
i = 0,
limit = s1.length,
match = 0,
idx;
while(i < s1.length)
// chomp the next character
c = s1.substr(i++, 1);
// find it in the second string
idx = s2.indexOf(c);
if (idx > -1)
// found it, add to the match
match++;
// assign the second string to remove the character we just matched
s2 = s2.substr(0, idx) + s2.substr(idx + 1);
else
// not found, not the same
return false;
return match === s1.length;
我认为技术上是可以这样解决的:
function anagram(s1, s2)
return s1.split("").sort().join("") === s2.split("").sort().join("");
我选择早期方法的原因是它对于较大的字符串更有效,因为如果检测到任何可能的失败情况,您不需要对任何一个字符串进行排序、转换为数组或循环遍历整个字符串。
【讨论】:
【参考方案5】:可能不是最有效的方法,但使用 es6 的清晰方法
function sortStrChars(str)
if (!str)
return;
str = str.split('');
str = str.sort();
str = str.join('');
return str;
const words = ["dell", "ledl", "abc", "cba", 'boo'];
function getGroupedAnagrams(words)
const anagrams = ; // abc:[abc,cba], dell:[dell, ledl]
words.forEach((word) =>
const sortedWord = sortStrChars(word);
if (anagrams[sortedWord])
return anagrams[sortedWord].push(word);
anagrams[sortedWord] = [word];
);
return anagrams;
const groupedAnagrams = getGroupedAnagrams(words);
for (const sortedWord in groupedAnagrams)
console.log(groupedAnagrams[sortedWord].toString());
【讨论】:
【参考方案6】:我在一次采访中遇到了这个问题。给定一个单词数组 ['cat', 'dog', 'tac', 'god', 'act'],返回一个包含所有字谜组合在一起的数组。确保字谜是唯一的。
var arr = ['cat', 'dog', 'tac', 'god', 'act'];
var allAnagrams = function(arr)
var anagrams = ;
arr.forEach(function(str)
var recurse = function(ana, str)
if (str === '')
anagrams[ana] = 1;
for (var i = 0; i < str.length; i++)
recurse(ana + str[i], str.slice(0, i) + str.slice(i + 1));
;
recurse('', str);
);
return Object.keys(anagrams);
console.log(allAnagrams(arr));
//["cat", "cta", "act", "atc", "tca", "tac", "dog", "dgo", "odg", "ogd", "gdo", "god"]
【讨论】:
【参考方案7】:最好和最简单的解决方法是使用 for 循环并将其遍历到每个字符串,然后将其结果存储在对象中。
这是解决方案:-
function anagram(str1, str2)
if (str1.length !== str2.length)
return false;
const result = ;
for (let i=0;i<str1.length;i++)
let char = str1[i];
result[char] = result[char] ? result[char] += 1 : result[char] = 1;
for (let i=0;i<str2.length;i++)
let char = str2[i];
if (!result[char])
return false;
else
result[char] = -1;
return true;
console.log(anagram('ronak','konar'));
【讨论】:
很好的解决方案!这比基于排序的解决方案要快。如果我没记错的话,这是时间复杂度 O(n),而排序最多应该是 O(n logn)。 :) 虽然它们可能更容易阅读...... 谢谢@Lurifaxel 这比第二种解决方案更干净。它通过创建一个对象来跟踪字符来使用频率模式,并使用保持 O(n) 时间的非嵌套循环。【参考方案8】:我知道这是一篇古老的帖子……但我最近在一次采访中被钉在了这个帖子上。所以,这是我的“新的和改进的”答案:
var AnagramStringMiningExample = function ()
/* Author: Dennis Baughn
* This has also been posted at:
* http://***.com/questions/909449/anagrams-finder-in-javascript/5642437#5642437
* Free, private members of the closure and anonymous, innner function
* We will be building a hashtable for anagrams found, with the key
* being the alphabetical char sort (see sortCharArray())
* that the anagrams all have in common.
*/
var dHash = ;
var sortCharArray = function(word)
return word.split("").sort().join("");
;
/* End free, private members for the closure and anonymous, innner function */
/* This goes through the dictionary entries.
* finds the anagrams (if any) for each word,
* and then populates them in the hashtable.
* Everything strictly local gets de-allocated
* so as not to pollute the closure with 'junk DNA'.
*/
(function()
/* 'dictionary' referring to English dictionary entries. For a real
* English language dictionary, we could be looking at 20,000+ words, so
* an array instead of a string would be needed.
*/
var dictionaryEntries = "buddy,pan,nap,toot,toto,anestri,asterin,eranist,nastier,ratines,resiant,restain,retains,retinas,retsina,sainter,stainer,starnie,stearin";
/* This could probably be refactored better.
* It creates the actual hashtable entries. */
var populateDictionaryHash = function(keyword, newWord)
var anagrams = dHash[keyword];
if (anagrams && anagrams.indexOf(newWord) < 0)
dHash[keyword] = (anagrams+','+newWord);
else dHash[keyword] = newWord;
;
var words = dictionaryEntries.split(",");
/* Old School answer, brute force
for (var i = words.length - 1; i >= 0; i--)
var firstWord = words[i];
var sortedFirst = sortCharArray(firstWord);
for (var k = words.length - 1; k >= 0; k--)
var secondWord = words[k];
if (i === k) continue;
var sortedSecond = sortCharArray(secondWord);
if (sortedFirst === sortedSecond)
populateDictionaryHash(sortedFirst, secondWord);
/*
/*Better Method for JS, using JS Array.reduce(callback) with scope binding on callback function */
words.reduce(function (prev, cur, index, array)
var sortedFirst = this.sortCharArray(prev);
var sortedSecond = this.sortCharArray(cur);
if (sortedFirst === sortedSecond)
var anagrams = this.dHash[sortedFirst];
if (anagrams && anagrams.indexOf(cur) < 0)
this.dHash[sortedFirst] = (anagrams + ',' + cur);
else
this.dHash[sortedFirst] = prev + ','+ cur;
return cur;
.bind(this));
());
/* return in a nice, tightly-scoped closure the actual function
* to search for any anagrams for searchword provided in args and render results.
*/
return function(searchWord)
var keyToSearch = sortCharArray(searchWord);
document.writeln('<p>');
if (dHash.hasOwnProperty(keyToSearch))
var anagrams = dHash[keyToSearch];
document.writeln(searchWord + ' is part of a collection of '+anagrams.split(',').length+' anagrams: ' + anagrams+'.');
else document.writeln(searchWord + ' does not have anagrams.');
document.writeln('<\/p>');
;
;
它的执行方式如下:
var checkForAnagrams = new AnagramStringMiningExample();
checkForAnagrams('toot');
checkForAnagrams('pan');
checkForAnagrams('retinas');
checkForAnagrams('buddy');
这是上面的输出:
toot 是 2 个集合的一部分 字谜:toto,toot。
pan 是 2 个集合的一部分 字谜:小睡,平底锅。
视网膜是 14 个集合的一部分 字谜: stearin,anestri,asterin,eranist,nastier,ratines,resiant,restain,retains,retinas,retsina,sainter,stainer,starnie。
好友没有字谜。
【讨论】:
【参考方案9】:我对这个旧帖子的解决方案:
// Words to match
var words = ["dell", "ledl", "abc", "cba"],
map = ;
//Normalize all the words
var normalizedWords = words.map( function( word )
return word.split('').sort().join('');
);
//Create a map: normalizedWord -> real word(s)
normalizedWords.forEach( function ( normalizedWord, index)
map[normalizedWord] = map[normalizedWord] || [];
map[normalizedWord].push( words[index] );
);
//All entries in the map with an array with size > 1 are anagrams
Object.keys( map ).forEach( function( normalizedWord , index )
var combinations = map[normalizedWord];
if( combinations.length > 1 )
console.log( index + ". " + combinations.join(' ') );
);
基本上我通过对每个单词的字符进行排序来规范化每个单词,因此 *** 将是 acefkloorstvw,在规范化的单词和原始单词之间建立一个映射,确定哪个规范化的单词超过附有 1 个字 -> 这是一个字谜。
【讨论】:
当然,文本规范化是将文本转换为单一规范形式的过程。这里的规范形式是对其字符进行排序的文本。【参考方案10】:我的两分钱。
这种方法对两个单词中的每个字符都使用 XOR。如果结果是 0,那么你有一个字谜。此解决方案假定区分大小写。
let first = ['Sower', 'dad', 'drown', 'elbow']
let second = ['Swore', 'add', 'down', 'below']
// XOR all characters in both words
function isAnagram(first, second)
// Word lengths must be equal for anagram to exist
if (first.length !== second.length)
return false
let a = first.charCodeAt(0) ^ second.charCodeAt(0)
for (let i = 1; i < first.length; i++)
a ^= first.charCodeAt(i) ^ second.charCodeAt(i)
// If a is 0 then both words have exact matching characters
return a ? false : true
// Check each pair of words for anagram match
for (let i = 0; i < first.length; i++)
if (isAnagram(first[i], second[i]))
console.log(`'$first[i]' and '$second[i]' are anagrams`)
else
console.log(`'$first[i]' and '$second[i]' are NOT anagrams`)
【讨论】:
【参考方案11】:我想到的答案:
function anagrams(stringA, stringB)
const aCharMap = buildCharMap(stringA);
const bCharMap = buildCharMap(stringB);
if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length)
return false;
for (let char in aCharMap)
if (aCharMap[char] !== bCharMap[char])
return false;
return true;
辅助函数:
function buildCharMap(str)
const charMap = ;
for (let char of str.replace(/[^\w]/g, ''))
charMap[char] = charMap[char] + 1 || 1;
return charMap;
但是如果您正在寻找最简单的方法:
function anagrams(stringA, stringB)
return cleanString(stringA) === cleanString(stringB);
function cleanString(str)
return str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('');
【讨论】:
【参考方案12】:function isAnagram(str1, str2)
var str1 = str1.toLowerCase();
var str2 = str2.toLowerCase();
if (str1 === str2)
return true;
var dict = ;
for(var i = 0; i < str1.length; i++)
if (dict[str1[i]])
dict[str1[i]] = dict[str1[i]] + 1;
else
dict[str1[i]] = 1;
for(var j = 0; j < str2.length; j++)
if (dict[str2[j]])
dict[str2[j]] = dict[str2[j]] - 1;
else
dict[str2[j]] = 1;
for (var key in dict)
if (dict[key] !== 0)
return false;
return true;
console.log(isAnagram("hello", "olleh"));
【讨论】:
【参考方案13】:我有一个简单的例子
function isAnagram(strFirst, strSecond)
if(strFirst.length != strSecond.length)
return false;
var tempString1 = strFirst.toLowerCase();
var tempString2 = strSecond.toLowerCase();
var matched = true ;
var cnt = 0;
while(tempString1.length)
if(tempString2.length < 1)
break;
if(tempString2.indexOf(tempString1[cnt]) > -1 )
tempString2 = tempString2.replace(tempString1[cnt],'');
else
return false;
cnt++;
return matched ;
调用函数将是isAnagram("Army",Mary);
函数将返回true
或false
【讨论】:
效果很好!你能解释一下逻辑吗?【参考方案14】:也许是这个?
function anagram (array)
var organized = ;
for (var i = 0; i < array.length; i++)
var word = array[i].split('').sort().join('');
if (!organized.hasOwnProperty(word))
organized[word] = [];
organized[word].push(array[i]);
return organized;
anagram(['kmno', 'okmn', 'omkn', 'dell', 'ledl', 'ok', 'ko']) // Example
它会返回类似的东西
dell: ['dell', 'ledl'],
kmno: ['kmno', okmn', 'omkn'],
ko: ['ok', ko']
这是您想要的简单版本,当然可以改进它以避免重复。
【讨论】:
【参考方案15】: let words = ["dell", "ledl","del", "abc", "cba", 'boo'];
//sort each item
function sortArray(data)
var r=data.split('').sort().join().replace(/,/g,'');
return r;
var groupObject=;
words.forEach((item)=>
let sorteditem=sortArray(item);
//Check current item is in the groupObject or not.
//If not then add it as an array
//else push it to the object property
if(groupObject[sorteditem])
return groupObject[sorteditem].push(item);
groupObject[sorteditem]=[sorteditem];
);
//to print the result
for(i=0;i<Object.keys(groupObject).length;i++)
document.write(groupObject[Object.keys(groupObject)[i]] + "<br>");
/* groupObject value:
abc: (2) ["abc", "cba"]
boo: ["boo"]
del: ["del"]
dell: (2) ["dell", "ledl"]
OUTPUT:
------
dell,ledl
del
abc,cba
boo
*/
【讨论】:
【参考方案16】:-
比较字符串长度,如果不相等,返回
false
创建字符哈希图,将字符计数存储在strA
例如Hello
--> H: 1, e: 1, l: 2, o: 1
遍历第二个字符串并在 Hashmap 中查找当前字符。如果不存在,则返回false
,否则将值递减1
如果以上都没有返回假,那么它一定是一个字谜
时间复杂度:O(n)
function isAnagram(strA: string, strB: string): boolean
const strALength = strA.length;
const strBLength = strB.length;
const charMap = new Map<string, number>();
if (strALength !== strBLength)
return false;
for (let i = 0; i < strALength; i += 1)
const current = strA[i];
charMap.set(current, (charMap.get(current) || 0) + 1);
for (let i = 0; i < strBLength; i += 1)
const current = strB[i];
if (!charMap.get(current))
return false;
charMap.set(current, charMap.get(current) - 1);
return true;
【讨论】:
不应该是charMap.set(current, -1);
是charMap.set(current,charMap.get(current) - 1);
?
@JustinThomas 好点,但实际上不需要。原因是条件检查两个字符串是否具有相同的长度。仍然感谢您指出这一点!
如果你有:catt 和 caat?
你是对的。我会调整我的代码。感谢您指出! +1【参考方案17】:
function findAnagram(str1, str2)
let mappedstr1 = , mappedstr2 = ;
for (let item of str1)
mappedstr1[item] = (mappedstr1[item] || 0) + 1;
for (let item2 of str2)
mappedstr2[item2] = (mappedstr2[item2] || 0) + 1;
for (let key in mappedstr1)
if (!mappedstr2[key])
return false;
if (mappedstr1[key] !== mappedstr2[key])
return false;
return true;
console.log(findAnagram("hello", "hlleo"));
【讨论】:
【参考方案18】:另一个例子,仅用于比较 2 个字符串的字谜。
function anagram(str1, str2)
if (str1.length !== str2.length)
return false;
else
if (
str1.toLowerCase().split("").sort().join("") ===
str2.toLowerCase().split("").sort().join("")
)
return "Anagram";
else
return "Not Anagram";
console.log(anagram("hello", "olleh"));
console.log(anagram("ronak", "konar"));
【讨论】:
请说明这段代码的作用和方式【参考方案19】:isAnagram 使用 reduce 的另一种解决方案
const checkAnagram = (orig, test) =>
return orig.length === test.length
&& orig.split('').reduce(
(acc, item) =>
let index = acc.indexOf(item);
if (index >= 0)
acc.splice(index, 1);
return acc;
throw new Error('Not an anagram');
,
test.split('')
).length === 0;
;
const isAnagram = (tester, orig, test) =>
try
return tester(orig, test);
catch (e)
return false;
console.log(isAnagram(checkAnagram, '867443', '473846'));
console.log(isAnagram(checkAnagram, '867443', '473846'));
console.log(isAnagram(checkAnagram, '867443', '475846'));
【讨论】:
【参考方案20】:var check=true;
var str="cleartrip";
var str1="tripclear";
if(str.length!=str1.length)
console.log("Not an anagram");
check=false;
console.log(str.split("").sort());
console.log("----------"+str.split("").sort().join(''));
if(check)
if((str.split("").sort().join(''))===((str1.split("").sort().join(''))))
console.log("Anagram")
else
console.log("not a anagram");
【讨论】:
区分大小写【参考方案21】:这是我的解决方案,它解决了一个测试用例,其中输入字符串不是字谜,可以从输出中删除。因此,输出仅包含字谜字符串。希望这会有所帮助。
/**
* Anagram Finder
* @params array wordArray
* @return object
*/
function filterAnagram(wordArray)
let outHash = ;
for ([index, word] of wordArray.entries())
let w = word.split("").sort().join("");
outHash[w] = !outHash[w] ? [word] : outHash[w].concat(word);
let filteredObject = Object.keys(outHash).reduce(function(r, e)
if (Object.values(outHash).filter(v => v.length > 1).includes(outHash[e])) r[e] = outHash[e]
return r;
, );
return filteredObject;
console.log(filterAnagram(['monk', 'yzx','konm', 'aaa', 'ledl', 'bbc', 'cbb', 'dell', 'onkm']));
【讨论】:
【参考方案22】:我最近在编码面试中遇到了这个问题,这是我的解决方案。
function group_anagrams(arr)
let sortedArr = arr.map(item => item.split('').sort().join(''));
let setArr = new Set(sortedArr);
let reducedObj = ;
for (let setItem of setArr)
let indexArr = sortedArr.reduce((acc, cur, index) =>
if (setItem === cur)
acc.push(index);
return acc;
, []);
reducedObj[setItem] = indexArr;
let finalArr = [];
for (let reduceItem in reducedObj)
finalArr.push(reducedObj[reduceItem].map(item => arr[item]));
return finalArr;
group_anagrams(['car','cra','rca', 'cheese','ab','ba']);
输出会是这样的
[
["car", "cra", "rca"],
["cheese"],
["ab", "ba"]
]
【讨论】:
【参考方案23】:我的解决方案有更多的代码,但它避免使用 .sort(),所以我认为这个解决方案的时间复杂度较低。相反,它对每个单词进行散列并比较散列:
const wordToHash = word =>
const hash = ;
// Make all lower case and remove spaces
[...word.toLowerCase().replace(/ /g, '')].forEach(letter => hash[letter] ? hash[letter] += 1 : hash[letter] = 1);
return hash;
const hashesEqual = (obj1, obj2) =>
const keys1 = Object.keys(obj1), keys2 = Object.keys(obj2);
let match = true;
if(keys1.length !== keys2.length) return false;
for(const key in keys1) if(obj1[key] !== obj2[key]) match = false; break;
return match;
const checkAnagrams = (word1, word2) =>
const hash1 = wordToHash(word1), hash2 = wordToHash(word2);
return hashesEqual(hash1, hash2);
console.log( checkAnagrams("Dormitory", "Dirty room") );
【讨论】:
【参考方案24】:/*This is good option since
logic is easy,
deals with duplicate data,
Code to check anagram in an array,
shows results in appropriate manner,
function check can be separately used for comparing string in this regards with all benefits mentioned above.
*/
var words = ["deuoll", "ellduo", "abc","dcr","frt", "bu","cba","aadl","bca","elduo","bac","acb","ub","eldou","ellduo","ert","tre"];
var counter=1;
var ele=[];
function check(str1,str2)
if(str2=="")
return false;
if(str1.length!=str2.length)
return false;
var r1=[...(new Set (str1.split('').sort()))];
var r2=[...(new Set (str2.split('').sort()))];
var flag=true;
r1.forEach((item,index)=>
if(r2.indexOf(item)!=index)
flag=false;
);
return flag;
var anagram=function ()
for(var i=0;i<words.length && counter!=words.length ;i++)
if(words[i]!="")
document.write("<br>"+words[i]+":");
counter++;
for(var j=i+1;j<words.length && counter !=words.length+1;j++)
if(check(words[i],words[j]))
ele=words[j];
document.write(words[j]+" ");
words[j]="";
counter++;
anagram();
【讨论】:
【参考方案25】:如果你只需要字谜计数
const removeDuplicatesAndSort = [...new Set(yourString.split(', '))].map(word => word.split('').sort().join())
const numberOfAnagrams = removeDuplicatesAndSort.length - [...new Set(removeDuplicatesAndSort)].length
【讨论】:
【参考方案26】:function isAnagram(str1, str2)
let count = 0;
if (str1.length !== str2.length)
return false;
else
let val1 = str1.toLowerCase().split("").sort();
let val2 = str2.toLowerCase().split("").sort();
for (let i = 0; i < val2.length; i++)
if (val1[i] === val2[i])
count++;
if (count == str1.length)
return true;
return false;
console.log(isAnagram("cristian", "Cristina"))
【讨论】:
【参考方案27】:const getAnagrams = (...args) =>
const anagrams = ;
args.forEach((arg) =>
const letters = arg.split("").sort().join("");
if (anagrams[letters])
anagrams[letters].push(arg);
else
anagrams[letters] = [arg];
);
return Object.values(anagrams);
【讨论】:
请解释您的代码的作用。解释将帮助当前和未来的访问者理解您的代码。 嗨@FriendlyBanana,它从问题中解决了问题。没有什么好解释的。【参考方案28】: function isAnagaram(str1, str2)
if(str1.length!== str2.length)
return false;
var obj1 = ;
var obj2 = ;
for(var arg of str1)
obj1[arg] = (obj1[arg] || 0 ) + 1 ;
for(var arg of str2)
obj2[arg] = (obj2[arg] || 0 ) + 1 ;
for( var key in obj1)
if(obj1[key] !== obj2[key])
return false;
return true;
console.log(isAnagaram('texttwisttime' , 'timetwisttext'));
【讨论】:
【参考方案29】:let validAnagram = (firstString, secondString) =>
if (firstString.length !== secondString.length)
return false;
let secondStringArr = secondString.split('');
for (var char of firstString)
charIndexInSecondString = secondString.indexOf(char);
if (charIndexInSecondString === -1)
return false;
secondString = secondString.replace(char, '');
return true;
【讨论】:
【参考方案30】:const arr = ['monk', 'konm', 'nkom', 'bbc', 'cbb', 'dell', 'ledl', 'llde'];
let anagram = ;
for (let i = 0; i<arr.length; i++)
const word = arr[i];
const sortedWord = word.split("").sort().join("");
let tempArray = [];
if(anagram[sortedWord])
tempArray = anagram[sortedWord].length==1?anagram[sortedWord]:[...anagram[sortedWord]];
tempArray.push(word);
anagram[sortedWord] = tempArray;
else
anagram[sortedWord] = [word];
console.log(Object.values(anagram));
【讨论】:
以上是关于javascript中的字谜查找器的主要内容,如果未能解决你的问题,请参考以下文章
php |字谜求解器通过 woldcard 查找不在原始搜索中的字母
javascript [438。查找字符串中的所有字谜] #tags:leetcode