在 Java 中打印字符串的所有排列

javaobject oriented programmingprogramming更新于 2025/7/13 12:28:17

以下是打印字符串所有排列的 Java 程序 −

示例

public class Demo{
   static void print_permutations(String my_str,String my_ans){
      if (my_str.length() == 0){
         System.out.print(my_ans + " ");
         return;
      }
      boolean my_arr[] = new boolean[26];
      for (int i = 0; i < my_str.length(); i++){
         char ch = my_str.charAt(i);
         String remaining_str = my_str.substring(0, i) + my_str.substring(i + 1);
          if (my_arr[ch - 'a'] == false)
          print_permutations(remaining_str, my_ans + ch);
         my_arr[ch - 'a'] = true;
      }
   }
    public static void main(String[] args){
      String my_str = "hey";
      System.out.println("字符串的排列为:");
      print_permutations(my_str, "");
   }
}

输出

字符串的排列为:
hey hye ehy eyh yhe yeh

名为 Demo 的类包含一个静态函数 ‘print_permutations’,用于检查字符串是否为空,如果为空,则打印输出。现在,一个名为 ‘my_arr’ 的布尔数组被分配大小为 36,其中默认存储 ‘false’ 值。每当使用字母表时,其在数组中的索引都会更改为 ‘true’。

使用 ‘for’ 循环遍历字符串的长度,并检查字符串的第 i 个字符。字符串中除第 i 个字符之外的剩余部分被赋值给名为"remaining_str"的字符串。如果该字符未被使用,则递归调用该函数。否则,不发生函数调用。在主函数中,定义一个字符串,并在此字符串上调用该函数。


相关文章


有用资源