Помогите пожалуйста написать код, который бы всеми возможными методами переставлял бы символы в строке. Например результатом для строки "ba" будет "ab" и "ba".
Вот вам вариант кода. Как по мне, то выглядит неплохо)
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i )
permutation(prefix str.charAt(i), str.substring(0, i) str.substring(i 1, n));
}
}
/**
* List permutations of a string.
*
* @param s the input string
* @return the list of permutations
*/
public static ArrayList permutation(String s) {
// The result
ArrayList res = new ArrayList();
// If input string length is 1, return {s}
if (s.length() == 1) {
res.add(s);
} else if (s.length() > 1) {
int lastIndex = s.length() - 1;
// Find out the last character
String last = s.substring(lastIndex);
// Rest of the string
String rest = s.substring(0, lastIndex);
// Perform permutation on the rest string and
// merge with the last character
res = merge(permutation(rest), last);
}
return res;
}
/**
* @param list a result of permutation, e.g. {"ab", "ba"}
* @param c the last character
* @return a merged new list, e.g. {"cab", "acb" ... }
*/
public static ArrayList merge(ArrayList list, String c) {
ArrayList res = new ArrayList<>();
// Loop through all the string in the list
for (String s : list) {
// For each string, insert the last character to all possible positions
// and add them to the new list
for (int i = 0; i <= s.length(); i) {
String ps = new StringBuffer(s).insert(i, c).toString();
res.add(ps);
}
}
return res;
}