Skip to content

Instantly share code, notes, and snippets.

@shahzadaazam
Created January 4, 2019 10:40
Show Gist options
  • Save shahzadaazam/ff1f52c53154fbde1238d7983ee91137 to your computer and use it in GitHub Desktop.
Save shahzadaazam/ff1f52c53154fbde1238d7983ee91137 to your computer and use it in GitHub Desktop.
Write a program to print all permutations of a given string
import java.util.*;
class PermuteString {
public static void main(String[] args) {
String abc = "ABC";
System.out.println(Solution.permutation(abc));
}
}
class Solution {
public static List<String> permutation (String str) {
List<String> result = new ArrayList<>();
permute(result, str, 0, str.length()-1);
return result;
}
public static void permute(List<String> list, String str, int start, int end) {
// System.out.println("hello");
if (start == end) {
list.add(new String(str));
} else {
for (int i = start; i <= end; i++) {
//swap
str = swap(str, start, i);
//permute
permute(list, str, start+1, end);
//replace
str = swap(str, start, i);
}
}
}
public static String swap(String str, int first, int second) {
char[] arr = str.toCharArray();
char temp = arr[second];
arr[second] = arr[first];
arr[first] = temp;
return new String(arr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment