生成字符串的所有k大小的字谜

时间:2015-09-22 22:41:45

标签: java python algorithm recursion permutation

如果您发现此问题的重复,请随时链接,因为我之前没有看过这个问题。

对于面试问题,我有以下内容:

1) Generate all anagrams of a string
   Ex. anagrams("dog") -> ["dog","dgo","odg","ogd","gdo","god"]

2) Generate all k-size anagrams of a string
   Ex. anagrams("dog",k = 2) -> ["do","od","dg","gd","go","og"]

我想出了一个解决方案(1),通过递归输入字符串减去它的第一个字符串,并将第一个字符插入到每个返回的字符串的每个位置:

def anagrams(word):
    if len(word) == 1:
        return [word]
    current = word[0]
    anags = []
    for anag in anagrams(word[1:]):
        anags += [anag[:i] + current + anag[i:] for i in range(len(anag) + 1)]
    return anags

任何人都可以使用签名def anagrams(word, k = None)或Java List<String> anagrams(String word, int k)为(2)提供Java或Python解决方案吗?

2 个答案:

答案 0 :(得分:1)

我相信这是正确的解决方案:

from itertools import permutations

def anagrams(word, k=None):
   return [''.join(p) for p in permutations(word, k)]

答案 1 :(得分:0)

  

对于面试问题,我有以下内容:

1) Generate all anagrams of a string
   Ex. anagrams("dog") -> ["dog","dgo","odg","ogd","gdo","god"]

2) Generate all k-size anagrams of a string
   Ex. anagrams("dog",k = 2) -> ["do","od","dg","gd","go","og"]
     

我想出了一个解决方法(1)通过递归输入字符串减去   它的第一个字符,并将第一个字符插入到每个位置   每个回复的字谜:

def anagrams(word):
    if len(word) == 1:
        return [word]
    current = word[0]
    anags = []
    for anag in anagrams(word[1:]):
        anags += [anag[:i] + current + anag[i:] for i in range(len(anag) + 1)]
    return anags
     

任何人都可以为(2)提供Java或Python解决方案   签名def anagrams(word, k = None)或Java List<String> anagrams(String word, int k)

是的,如果你已经做过1),这几乎是微不足道的。

只列出相同的字谜列表,但只显示第一个“k”字符。例如:

[狗,DGO,ODG,OGD,GDO,高格]

变为:

[做,DG,OD,OG,GD,去]

(被视为一组)与您的示例输出相同2)。即,相同的k-anagrams列表,但顺序不同。

def kanagrams(word,k):
    return [x[0:k] for x in set(anagram(word))]