📜  打印Java字符串的所有排列

📅  最后修改于: 2021-05-24 19:43:37             🧑  作者: Mango

给定一个字符串str ,任务是打印str的所有排列。就排列的顺序而言,排列是一组对象的全部或一部分的排列。例如,单词“ bat”和“ tab”代表相似的三个字母单词的两个不同的排列(或排列)。

例子:

方法:编写一个递归函数,以打印给定字符串的每个排列。终止条件为传递的字符串为空时。

下面是上述方法的实现:

// Java program to print all the permutations
// of the given string
public class GFG {
  
    // Function to print all the permutations of str
    static void printPermutn(String str, String ans)
    {
  
        // If string is empty
        if (str.length() == 0) {
            System.out.print(ans + " ");
            return;
        }
  
        for (int i = 0; i < str.length(); i++) {
  
            // ith character of str
            char ch = str.charAt(i);
  
            // Rest of the string after excluding 
            // the ith character
            String ros = str.substring(0, i) + 
                         str.substring(i + 1);
  
            // Recurvise call
            printPermutn(ros, ans + ch);
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s = "abb";
        printPermutn(s, "");
    }
}
输出:
abb abb bab bba bab bba

何时需要区分排列。

例子:

方法:编写一个可打印不同排列的递归函数。制作一个大小为’26’的布尔数组,该数组说明所使用的字符。如果尚未使用该字符,则将进行递归调用。否则,请勿拨打电话。终止条件为传递的字符串为空时。

下面是上述方法的实现:

// Java program to print all the permutations
// of the given string
public class GFG {
  
    // Function to print all the distinct
    // permutations of str
    static void printDistinctPermutn(String str, 
                                     String ans)
    {
  
        // If string is empty
        if (str.length() == 0) {
  
            // print ans
            System.out.print(ans + " ");
            return;
        }
  
        // Make a boolean array of size '26' which
        // stores false by default and make true 
        // at the position which alphabet is being
        // used
        boolean alpha[] = new boolean[26];
  
        for (int i = 0; i < str.length(); i++) {
  
            // ith character of str
            char ch = str.charAt(i);
  
            // Rest of the string after excluding 
            // the ith character
            String ros = str.substring(0, i) + 
                         str.substring(i + 1);
  
            // If the character has not been used 
            // then recursive call will take place. 
            // Otherwise, there will be no recursive
            // call
            if (alpha[ch - 'a'] == false)
                printDistinctPermutn(ros, ans + ch);
            alpha[ch - 'a'] = true;
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s = "geek";
        printDistinctPermutn(s, "");
    }
}
输出:
geek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg