首页 文章资讯内容详情

Java程序打印字符串的所有排列

2026-06-04 1 花语

以下是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”循环用于遍历字符串的长度,并检查字符串的ith个字符。字符串的其余部分(不带第ith个字符)将分配给名为“remaining_str”的字符串。如果未使用该字符,则会对该函数进行递归调用。否则,不会发生任何函数调用。在main函数中,定义了一个字符串,并在该字符串上调用了该函数。