public class StringPermutations {
public static void main(String[] args) {
String str = "ABC";
System.out.println("Permutations of " + str + ":");
permute(str, 0, str.length() - 1);
}
public static void permute(String str, int left, int right) {
if (left == right) {
System.out.println(str);
} else {
for (int i = left; i <= right; i++) {
str = swap(str, left, i);
permute(str, left + 1, right);
str = swap(str, left, i);
}
}
}
public static String swap(String str, int i, int j) {
char[] charArray = str.toCharArray();
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}
Permutations of ABC:ABC
ACB
BAC
BCA
CBA
CAB
str
. We then call the permute()
method, which takes three arguments
: the string str
, the left index left
, and the right index right
. The permute()
method computes all permutations of the substring of str
that starts at index left
and ends at index right
.permute()
method first checks whether left
is equal to right
. If they are equal, it prints the current permutation of str
to the console. Otherwise, it loops through all possible positions of the character at index left
, and recursively computes all permutations of the substring that starts at index left + 1
and ends at index right
. It also swaps the characters at positions left
and i
in str
before and after the recursive call to ensure that all possible permutations are computed.swap()
method is a helper method that takes a string str
and two indices i
and j
, and swaps the characters at positions i
and j
in str
. It then returns the modified string.