Distinct permutations of a string containing duplicates using HashSet in Java
Last Updated :
19 Sep, 2019
Given a string str that may contain duplicate characters, the task is to print all the distinct permutations of the given string such that no permutation is repeated in the output.
Examples:
Input: str = “ABA”
Output:
ABA
AAB
BAA
Input: str = “ABC”
Output:
ABC
ACB
BAC
BCA
CBA
CAB
Approach: An approach to generate all the permutations of a given string has been discussed in this article. All the permutations generated by this approach can be stored in a HashSet in order to avoid duplicates.
Below is the implementation of the above approach:
import java.util.HashSet;
public class GFG {
public static HashSet<String> h = new HashSet<String>();
public static void permute( char s[], int i, int n)
{
if (i == n) {
if (!(h.contains(String.copyValueOf(s)))) {
h.add(String.copyValueOf(s));
System.out.println(s);
}
}
else {
for ( int j = i; j <= n; j++) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
permute(s, i + 1 , n);
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
public static void main(String args[])
{
char s[] = { 'A' , 'B' , 'A' };
permute(s, 0 , s.length - 1 );
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...