×

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given string.

For example let ‘rat’ be the string and the list of all possible permutations for string are:

  1. rat
  2. art
  3. tar
  4. rta
  5. tra
  6. atr

In order to solve these type of problems first we need to learn backtracking algorithm.

Backtracking Algorithm

Algorithm

1.Establish a string.

2.Fix one character, then switch the others.

3.For the remaining characters, call permutationFunction().

4.Go back and switch the characters once again.

Java Program To Print Permutations Of String

Procedure

  1. Replace the rest of the characters with the character in the first position after fixing the first character. Similar to ABC, the first iteration results in the formation of three strings: ABC, BAC, and CBA by replacing A with A, B, and C, respectively. For the remaining characters, repeat step 1 by fixing the second character B and so forth.
  2. Switch again to return to your original position. For instance, starting with ABC, we would create ABC by adjusting B once more before going back and switching B and C. We now have ABC and ACB.
  3. Repeat these processes for BAC and CBA to obtain all possible combinations.

If repetition is allowed we can use recursion method to get the output

Repetition- Repeating same strings in the output

Recursion Method 1

In this method the function is called recursively until the string passed gets empty (termination condition). Using this method we will get repeated permutations of the string.

Java program to print all the permutations of the given string

public class Main {
static void printStrings(String str, String ans)
{
// If string is empty
if (str.length() == 0) {
System.out.println(ans + " ");
return;
}
for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);
String ros = str.substring(0, i) +str.substring(i + 1);
// Calling the function recursively
printStrings(ros, ans + ch);
}
}// printStrings
//Main method
public static void main(String[] args)
{
String s = "abb";
printStrings(s, "");
} 
}//main

Output

Java Program To Print Permutations Of String

Explanation

In the program above, we are calling the function called "printStrings" with the string "abb" and we are supplying another empty string as a parameter to append the string's remaining characters. The function ends by producing an empty string as output and the programme is ended if the string is empty. Using a for loop, we will go through the string, adding each additional character apart from the one at position I and calling the function repeatedly until the string is empty.

Recursion Method 2

To avoid the repetitions of the string we will use another recursion method.

Program to print all different permutations of string

// Java program to print all the permutations of the given string
public class Main {
    static void Permutations(String s1,String ans)
    {
        if (s1.length() == 0) {
            System.out.println(ans + " ");
            return;
        }
        boolean a[] = new boolean[26];
        for (int i = 0; i < s1.length(); i++) {
            char c = s1.charAt(i);
            String ros = s1.substring(0, i) +s1.substring(i + 1);
            if (a[c - 'a'] == false)
                Permutations(ros, ans + c);
            a[c- 'a'] = true;
        }
    }
    public static void main(String[] args)
    {
        String s = "java";
        Permutations(s,"");
    }
}

Output

Java Program To Print Permutations Of String

Explanation

Make a 26-character long Boolean array that tracks the character being used. The recursive call will be made if the character hasn't been utilised. If not, don't place any calls. When the given string is empty, the sentence will end.

3.Iterative Approach: Using Collection

import java.util.ArrayList;
import java.util.List;
 
class Main
{
    public static void Permutations(String s)
    {
        if (s == null || s.length() == 0) 
        {
            return;
        }
        List<String> result = new ArrayList<>();
        result.add(String.valueOf(s.charAt(0)));
        for (int i = 1; i < s.length(); i++)
        {
            for (int j = result.size() - 1; j >= 0 ; j--)
            {
                String s1 = result.remove(j);
                for (int k = 0; k <= s1.length(); k++)
                {
                    result.add(s1.substring(0, k) + s.charAt(i) + s1.substring(k));
                }
            }
        }
        System.out.println(result);
    }
    public static void main(String[] args)
    {
        String string = "QWE";
        Permutations(string);
    }
}

Output

Java Program To Print Permutations Of String

Related Topics

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.