Recursive Method for String Permutations in Java

Beanie Leung :

I'm trying to write a recursive program: to compute all strings of length n that can be formed from all the characters given in string, but none of the strings listed in sub are allowed to appear as substrings.

This is the program I have written so far, but it doesn't yet implement the restriction of sub, it only computes the permutations of string.

    public static void method(String string)
    {
        method(string, "");
    }
    public static void method(String string, String soFar)
    {
        if (string.isEmpty())
        {
            System.err.println(soFar + string);
        }
        else
        {
            for (int i = 0; i < string.length(); i++)
            {
                method(string.substring(0, i) + string.substring(i + 1, string.length()), soFar + string.charAt(i));
            }
        }
    }
Mirea Radu :

From your example I see that you want all permutations with repetition for n characters, but your code generates all permutations without repetition for all characters.

This should solve your problem as stated in the example:

    public static List<String> method(String string, int n, List<String> sub)
    {
        List<String> results = new ArrayList<>();
        method(string, n, "", sub, results);
        return results;
    }
    private static void method(String string, int n,  String soFar, List<String> sub, List<String> results)
    {
        for (String s: sub)
        {
            if(soFar.length() >= s.length() && soFar.substring(soFar.length() - s.length()).equals(s))
            {
                return;
            }
        }
        if (soFar.length() == n)
        {
            results.add(soFar);
        }
        else
        {
            for (int i = 0; i < string.length(); i++)
            {
                method(string, n, soFar + string.charAt(i), sub, results);
            }
        }
    }

Also, it's redundant to append string when string is empty.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=277556&siteId=1