Write a function that will find all permutations of a given string.

devquora
devquora

Posted On: Dec 24, 2020

 

A function that will find all permutations of a given string is as follows:

public static Set permutationFinder(String str) {
        Set perm = new HashSet();
        if (str == null) {
            return null;
        } else if (str.length() == 0) {
            perm.add("");
            return perm;
        }
        char initial = str.charAt(0); // first character
        String rem = str.substring(1); // Full string without first character
        Set words = permutationFinder(rem);
        for (String strNew : words) {
            for (int i = 0;i<=strNew.length();i++){
                perm.add(charInsert(strNew, initial, i));
            }
        }
        return perm;
    }

    public static String charInsert(String str, char c, int j) {
        String begin = str.substring(0, j);
        String end = str.substring(j);
        return begin + c + end;
    }


    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Amazon Support Engineer Interview Questions

    Explain What is STP?

    The STP also stands for Spanning Tree Protocol constructs a loop-free logical topography for Ethernet networks. It is a ..

    Amazon Support Engineer Interview Questions

    Write a function to check if a number is prime?

    A prime number is a whole number greater than 1, which is only divisible by 1 and itself. // function check whether a number // is prime or not bool isPrime(int n) { // Corner case if (n...

    Amazon Support Engineer Interview Questions

    Write a regular expression to validate phone number in  XXX-XXX-XXXX format?

    A regular expression to validate phone number in XXX-XXX-XXXX format is follows: /^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/...