anagram algorithm

我是研究僧i 提交于 2019-12-04 18:44:41

The question looks like generating the list of permutations; (Anagrams are a subset of permutations, which form a meaningful word). n! Permutations can be generated in chronological order using the approach of STL's next_permutation, (linear time complexity per permutation); You can find the discussion of this algorithm here: http://marknelson.us/2002/03/01/next-permutation/ ; STL's algorithm can even handle duplicates and the naive swap algorithm fails in this case.

For a indepth discussion on generating permutations, you can go through Donald Knuth's Generating all Perumutations section of TAOCP.

Carsten

here is a straight-forward implementation, just in case you need one:

IEnumerable<List<T>> Permutations<T>(List<T> items)
{
    if (items.Count == 0) yield return new List<T>();

    var copy = new List<T>(items);
    foreach (var i in items)
    {
        copy.Remove(i);
        foreach (var rest in Permutations(copy))
        {
            rest.Insert(0, i);
            yield return rest;
        }
        copy.Insert(0, i);
    }

}

IEnumerable<string> Anagrams(string word)
{
    return Permutations(word.ToCharArray().ToList()).Select(x => new String(x.ToArray()));
}

The answer concerning the time-complexity gave Adithya. To understand their answer you have to know that there are n! = 1*2*...*n permutations for n items. My algorithm is a proof for that (or based on the straight forward proof)

Backtracking is the fastest way to go, When you want all the anagrams for a text, it means you need all the n! permutations of it. So assuming printing/generating each permutation takes O(1) atleast, your algorithm would take O(n!) anyways, hence you cant do quicker than a backtracking solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!