Java String Permutation nextPermutation(String f)

Here you can find the source of nextPermutation(String f)

Description

Create next permutation based on provided.

License

Apache License

Return

next permutation.

Declaration

public static String nextPermutation(String f) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*  ww  w .java  2  s  . com*/
     * Create next permutation based on provided. a -> b <br/>
     * z -> aa <br/>
     * aa -> ab <br/>
     * az -> ba <br/>
     * bz -> ca <br/>
     * zz -> aaa <br/>
     * 
     * @return next permutation.
     */
    public static String nextPermutation(String f) {
        boolean onlyZ = true;
        for (int i = 0; i < f.length(); ++i)
            if (f.charAt(i) != 'z')
                onlyZ = false;
        if (onlyZ) {
            String s = "";
            for (int i = 0; i <= f.length(); ++i)
                s = s + 'a';
            return s;
        }
        for (int i = f.length() - 1; i > -1; --i)
            if (f.charAt(i) != 'z') {
                if (i == f.length() - 1) {
                    char last = (char) (f.charAt(i) + 1);
                    return f.substring(0, f.length() - 1) + new Character(last).toString();
                } else {
                    char symb = (char) (f.charAt(i) + 1);
                    String postfix = "";
                    for (int u = i + 1; u < f.length(); ++u) {
                        postfix += "a";
                    }
                    return f.substring(0, i) + new Character(symb).toString() + postfix;
                }
            }
        return f;
    }
}