What is an elegant way to find all the permutations of a string. E.g. ba
, would be ba
and ab
, but what about abcdefgh
? Is there any example Java implementation?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
One of the simple solution could be just keep swapping the characters recursively using two pointers.
Let's use input
abc
as an example.Start off with just the last element (
c
) in a set (["c"]
), then add the second last element (b
) to its front, end and every possible positions in the middle, making it["bc", "cb"]
and then in the same manner it will add the next element from the back (a
) to each string in the set making it:Thus entire permutation:
Code:
Here are two c# versions (just for reference): 1. Prints all permuations 2. returns all permutations
Basic gist of the algorithm is (probably below code is more intuitive - nevertheless, here is some explanation of what below code does): - from the current index to for the rest of the collection, swap the element at current index - get the permutations for the remaining elements from next index recursively - restore the order, by re-swapping
Note: the above recursive function will be invoked from the start index.
version 2 (same as above - but returns the permutations in lieu of printing)
Unit Tests
A java implementation to print all the permutations of a given string considering duplicate characters and prints only unique characters is as follow:
A very basic solution in Java is to use recursion + Set ( to avoid repetitions ) if you want to store and return the solution strings :