public class PermutationGenerator
{
  private String word;
  private int current;
  private PermutationGenerator tailGenerator;

  public PermutationGenerator(String word) {
    this.word = word;
    this.current = 0;
    if (this.word.length() > 1) {
      this.tailGenerator =
          new PermutationGenerator(this.word.substring(1));
    }
  }

  public String nextPermutation() {
    if (this.word.length() == 1) {
      this.current++;
      return this.word;
    }

    String r = this.word.charAt(this.current) +
               this.tailGenerator.nextPermutation();

    if (!this.tailGenerator.hasMorePermutations()) {
      this.current++;
      if (this.current < this.word.length()) {
        String tailString = this.word.substring(0, this.current)
                            + this.word.substring(this.current+1);
        this.tailGenerator = new PermutationGenerator(tailString);
      }
    }
    return r;
  }

  public boolean hasMorePermutations()
  {
    return this.current < this.word.length();
  }
}
