permute String - Java java.lang

Java examples for java.lang:String Algorithm

Description

permute String

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String beginningString = "abc";
        String endingString = "cba";
        permuteString(beginningString, endingString);
    }//  w ww . j  ava2 s .c  o m

    public static void permuteString(String beginningString,
            String endingString) {
        if (endingString.length() <= 1)
            System.out.println(beginningString + endingString);
        else
            for (int i = 0; i < endingString.length(); i++) {
                try {
                    System.out.println("sub from 0 to i "
                            + endingString.substring(0, i));
                    System.out.println("end string for i+1"
                            + endingString.substring(i + 1));
                    String newString = endingString.substring(0, i)
                            + endingString.substring(i + 1);
                    System.out.println("new String " + newString);
                    permuteString(beginningString + endingString.charAt(i),
                            newString);
                } catch (StringIndexOutOfBoundsException exception) {
                    exception.printStackTrace();
                }
            }
    }
}

Related Tutorials