嗨,这是我在求职面试中遇到的一个基本问题,我试图使用Java获取输入字符串的所有排列,遗憾的是我无法使其工作。
import java.util.Scanner;
public class Test2 {
static void permute(char[] x, int y){
if (y == x.length)
{
for(int i = 0; i < x.length; i++){
System.out.print(x[y]);
}
}
else {
for (int i = y; i < x.length;i++)
{
char temp = x[y];
x[y] = x[i];
x[i] = temp;
permute(x, y + 1);
temp = x[y];
x[y] = x[i];
x[i] = temp;
}
}
}
public static void main(String [] Args){
Scanner scan = new Scanner (System.in);
System.out.println("Input any word :");
String word = scan.nextLine();
int n = word.length();
char [] sequence = new char[n];
for (int i = 0; i < n ; i++)
sequence[i] = scan.next().charAt(0);
System.out.println("These are the permutations: ");
permute(sequence,0);
}
}
答案 0 :(得分:0)
我正在给一个关于C的程序,我希望将它转换成您选择的语言会变得非常困难。
来源: - http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
答案 1 :(得分:0)
/**
* Generates all permutations of a string given that all characters of that string are different.
*
* @param s
* the input string
*
* @return a set of all permutations from the given string
*/
public Set<String> generatePermutations(String s) {
Set<String> permutations = new HashSet<String>();
//Handling error scenarios
if (s == null) {
return null;
} else if (s.length() == 0) {
permutations.add("");
return permutations;
}
char firstCharacter = s.charAt(0); // first character
String remaining = s.substring(1); // Full string without first character
Set<String> words = generatePermutations(remaining);
for (String word : words) {
for (int i = 0; i <= word.length(); i++) {
permutations.add(insertCharacter(word, firstCharacter, i));
}
}
return permutations;
}
/**
* Given a collection of numbers that might contain duplicates, return all possible unique permutations. For
* example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1].
*
* @param numbers
* the collection of integer numbers
*
* @return a set of all unique combinations from the given collection of numbers
*/
public HashSet<List<Integer>> generateCombinations(List<Integer> numbers) {
Preconditions.checkNotNull(numbers);
HashSet<List<Integer>> combinations = new HashSet<List<Integer>>();
if (numbers.size() == 0) {
combinations.add(new ArrayList<Integer>());
return combinations;
}
int size = numbers.size();
int lastNumber = numbers.get(size - 1);
numbers.remove(size - 1);
HashSet<List<Integer>> elements = generateCombinations(numbers);
for (List<Integer> element : elements) {
for (int i = 0; i < size; i++) {
List<Integer> temp = new ArrayList<>(element);
temp.add(i, lastNumber);
// two Lists of the same base type (e.g. ArrayList) with the same content, in the same order, will compare as equal.
// // http://stackoverflow.com/questions/16657905/adding-arrays-with-same-values-to-hashset-results-in-duplicate-items
combinations.add(temp);
}
}
return combinations;
}