Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am reading a book on DSA, and the author explains how to generate the permutation of strings using recursion. I want to know if there are better ways of doing the same, unless this is the best solution. Also, could someone help me understand the time-complexity of this algorithm? Recursion is something I use very rarely but am trying to learn about now.

public class Anagrams {
private char[] chArray;
private int size;
private static int count;

public Anagrams(String anagramString, int size) {
    if (size <= 0) {
        System.out.println("Please enter a valid String");
    }
    chArray = anagramString.toCharArray();
    this.size = size;

}

public static void main(String args[]) {
    String str = "dogs";
    Anagrams anagramGenerator = new Anagrams(str, str.length());
    anagramGenerator.generateAnagrams(str.length());

}

public void generateAnagrams(int newSize) {
    if (newSize == 1)
        return;

    for (int i = 0; i < newSize; i++) {
        generateAnagrams(newSize - 1);
        if (newSize == 2)
            displayWord();
        rotate(newSize);
    }

}

private void rotate(int newSize) {
    // TODO Auto-generated method stub
    int position = size - newSize;
    char tempCh = chArray[position];
    int i;
    for (i = position + 1; i < size; i++) {
        chArray[i - 1] = chArray[i];
    }
    chArray[i - 1] = tempCh;

}

private void displayWord() {
    // TODO Auto-generated method stub
    String word = "";
    count++;
    for (int i = 0; i < chArray.length; i++) {
        word += chArray[i];
    }
    System.out.println(count + ")" + word);
}
}
share|improve this question

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.