Algorithm to list unique permutations of string with duplicate letters

后端 未结 3 1352
星月不相逢
星月不相逢 2020-11-30 11:48

For example, string \"AAABBB\" will have permutations: \"ABAABB\", \"BBAABA\", \"ABABAB\", etc

What\'s a good algorithm for generating the permutations? (And what\

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 12:30

    This is not full answer, just an idea.

    If your strings has fixed number of only two letters I'll go with binary tree and good recursion function. Each node is object that contains name with prefix of parent name and suffix A or B furthermore it have numbers of A and B letters in the name.

    Node constructor gets name of parent and number of A and B from parent so it needs only to add 1 to number of A or B and one letter to name.

    It doesn't construct next node if there is more than three A (in case of A node) or B respectively, or their sum is equal to the length of starting string.

    Now you can collect leafs of 2 trees (their names) and have all permutations that you need.

    Scala or some functional language (with object-like features) would be perfect for implementing this algorithm. Hope this helps or just sparks some ideas.

提交回复
热议问题