📜  Java程序来计算字符串的所有排列

📅  最后修改于: 2020-09-26 18:02:03             🧑  作者: Mango

在此示例中,我们将学习计算Java中字符串的所有排列。

字符串手段所有可以通过互换字符串的字符的位置来形成的可能的新字符串的排列。例如, 字符串 ABC具有排列[ABC,ACB,BAC,BCA,CAB,CBA]

示例:Java程序获取字符串的所有排列
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

class Main {
  public static Set getPermutation(String str) {

    // create a set to avoid duplicate permutation
    Set permutations = new HashSet();

    // check if string is null
    if (str == null) {
      return null;
    } else if (str.length() == 0) {
      // terminating condition for recursion
      permutations.add("");
      return permutations;
    }

    // get the first character
    char first = str.charAt(0);

    // get the remaining substring
    String sub = str.substring(1);

    // make recursive call to getPermutation()
    Set words = getPermutation(sub);

    // access each element from words
    for (String strNew : words) {
      for (int i = 0;i<=strNew.length();i++){

        // insert the permutation to the set
        permutations.add(strNew.substring(0, i) + first + strNew.substring(i));
      }
    }
    return permutations;
  }

  public static void main(String[] args) {

    // create an object of scanner class
    Scanner input = new Scanner(System.in);

    // take input from users
    System.out.print("Enter the string: ");
    String data = input.nextLine();
    System.out.println("Permutations of " + data + ": \n" + getPermutation(data));
    }
}

输出

Enter the string: ABC
Permutations of ABC: 
[ACB, BCA, ABC, CBA, BAC, CAB]

在Java中,我们使用了递归来计算字符串的所有排列。在这里,我们将排列存储在集合中。因此,不会有重复的排列。