Popular Posts

Tuesday, July 19, 2011

Permutation of Strings

Problem:
Write a method to compute all permutations of a string.


Solution:

Let’s assume a given string S represented by the letters A1, A2, A3, ... , An
To permute set S, we can select the first character, A1, permute the remainder of the string to get a new list. Then, with that new list, we can “push” A1 into each possible position.
For example, if our string is “abc”, we would do the following:
1. Let first = “a” and let remainder = “bc”
2. Let list = permute(bc) = {“bc”, “cd”}
3. Push “a” into each location of “bc” (--> “abc”, “bac”, “bca”) and “cb” (--> “acb”, “cab”, “cba”)
4. Return our new list



Complexity: O(n!)


Code:



Another approach:



With Repeated characters in the input string:

In a loop,a particular character must be swapped with current index only once,

No comments:

Post a Comment