Gets all possible permutations of a string - Java java.lang

Java examples for java.lang:String Algorithm

Description

Gets all possible permutations of a string

Demo Code


//package com.java2s;

import java.util.*;

public class Main {
    /**/* ww  w . ja v  a2  s  .c  om*/
     * Gets all possible permutations of a string
     * @param str The string to permutate
     * @return An ArrayList of all possible permutations
     */
    public static LinkedList<String> getPermutations(String str) {
        LinkedList<String> result = new LinkedList<String>();

        if (str.length() == 1) {
            result.add(str);
            return result;
        } else {
            char first = str.charAt(0);
            String rest = str.substring(1);

            List<String> permOfRest = getPermutations(rest);

            for (String perm : permOfRest) {
                List<String> additions = insertAtAllPositions(first, perm);
                result.addAll(additions);
            }
        }
        return result;
    }

    /**
     * Inserts the char, c, back into the permutation, s
     * @param c The char to insert back
     * @param s The string to insert the char into
     * @return The permutation with the leading char, c
     */
    private static List<String> insertAtAllPositions(char c, String s) {
        List<String> result = new ArrayList<String>();
        for (int i = 0; i < s.length(); i++) {
            result.add(s.substring(0, i) + c + s.substring(i));
        }
        return result;
    }
}

Related Tutorials