给定一个字符串数组,返回所有团体字符串是字谜 [英] Given a string array, return all groups of strings that are anagrams

查看:159
本文介绍了给定一个字符串数组,返回所有团体字符串是字谜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串数组,返回所有团体都字谜字符串。

Given a string array, return all groups of strings that are anagrams.

我的解决方案:

有关阵列中的每个串词,排序它0(M LG米),m是一个单词的平均长度。

For each string word in the array, sort it O(m lg m), m is the average length of a word.

建立了一个哈希表<字符串列表>。

Build up a hash Table < string, list >.

把排序的字到哈希表的关键,也是生成所有排列(O(M!))的字样,搜索每个排列在字典中(A preFIX树图)与O(M)如果它是在词典,把(O(1))送入哈希表,以便所有置换的话被放入列表中使用相同的密钥。

Put the sorted word into the hash table as key and also generate all permutations (O(m!)) of the word, search each permutation in a dictionary (a prefix tree map) with O(m), if it is in the dictionary, put (O(1)) it into the hash table so that all permutated words are put into the list with the same key.

完全,O(N * M * LG m * m的!)时间和O(N * M!)空间,n是给定的数组的大小。

Totally, O(n * m * lg m * m!) time and O(n* m!) space , n is the size of the given array.

如果m是非常大的,这是效率不高,米! 。

If m is very large, it is not efficient , m! .

没有更好的办法?

感谢

推荐答案

我们定义了一个字母,其中包含每一个字母,我们可能在我们的词库。接下来,我们需要一个不同的素每个字母表的字母,我建议使用最小的,你可以找到。

We define an alphabet, which contains every letter we may have in our wordlist. Next, we need a different prime for each of the letters in the alphabet, I recommend using the smallest you can find.

这将使我们有以下映射: {一个=> 2时,b => 3中,c => 5,D => 7,等}

That would give us the following mapping: { a => 2, b => 3, c => 5, d => 7, etc }

现在计数要重新present为整字的字母,并建立你的结果的整数如下:

Now count the letters in the word you want to represent as integer, and build your result integer as follows:

伪code:

result = 1
for each letter:
....result *= power(prime[letter], count(letter,word)

一些例子:

AAAA => 2 ^ 4

aaaa => 2^4

AABB => 2 ^ 2 * 3 ^ 2 = BBAA =巴巴= ...

aabb => 2^2 * 3^2 = bbaa = baba = ...

等等。

所以,你将不得不重新presenting在你的字典中的每个单词,并要检查就可以被转换成整数字一个整数。因此,如果n是你的单词表和k的大小是最长的单词将需要O(NK),以建立新的字典和O(K),检查了一个新词的大小。

So you will have an integer representing each word in your dictionary and the word you want to check will be able to be converted to an integer. So if n is the size of your wordlist and k is the size of the longest word it will take O(nk) to build your new dictionary and O(k) to check a new word.

Hackthissite.com有一个编程的挑战是:给定一个炒字,看它在字典,看看它的任何字谜是在字典。还有就是好文章在一个有效的解决方案,从我借的回答这个问题,它也进入细节进一步的优化。

Hackthissite.com has a programming challenge which is: Given a scrambled word, look it up in a dictionary to see if any anagrams of it are in the dictionary. There is a good article on an efficient solution to the problem from which I have borrowed the answer, it also goes into detail on further optimisations.

这篇关于给定一个字符串数组,返回所有团体字符串是字谜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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