如何使用java显示给定String的组合?

时间:2016-12-13 11:33:45

标签: java

如何使用java显示给定String的组合?

例如,

输入:abc 输出:

cab
abc
cba
bac
acb

1 个答案:

答案 0 :(得分:0)

import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;

public class Combinations {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String str = sc.next();
    char[] ch = str.toCharArray();
    char temp ;
    HashSet<String> al=new HashSet<String>();  
    for (int i = 0;i < str.length();i++) {
      for (int j = 0;j < str.length();j++) {
        temp = ch[i];
        ch[i] = ch[j];
        ch[j] = temp;
        al.add(String.valueOf(ch));
        temp = ' ';
      }
    }
    Iterator<String> itr=al.iterator();  
    while(itr.hasNext()){  
     System.out.println(itr.next());  
    }  
  }
}