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

要理解此示例,您应了解以下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<String> getPermutation(String str) {

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

    // 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<String> 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 中,我们使用递归来计算字符串的所有排列。我们将排列存储在 set 集合中。因此,不会有重复的排列。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战