prints all permutations of a given string. - Java java.lang

Java examples for java.lang:String Algorithm

Description

prints all permutations of a given string.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String inputString = "java2s.com";
        permutation(inputString);/*from   w  w  w . j a  v a  2  s.c  o  m*/
    }

    /***
     * permutation(final String inputString) 
     * permutation(final String inputString) prints all permutations of a given string.
     * @param inputString
     */
    public static void permutation(final String inputString) {
        permut("", inputString);
    }

    /***
     * This is the recursive call for getting permutations of the string.
     * @param firstString
     * @param secondString
     */
    private static void permut(String firstString, String secondString) {
        if (secondString.length() == 0) {
            System.out.println(firstString);
        } else
            for (int i = 0; i < secondString.length(); i++) {
                permut(firstString + secondString.charAt(i),
                        secondString.substring(0, i)
                                + secondString.substring(i + 1,
                                        secondString.length()));
            }
    }
}

Related Tutorials