您的位置:首页 > 编程语言 > Java开发

字符串字母全排列练习

2016-06-29 20:26 274 查看

[b]输入例子:[/b]
WHL


[b]输出例子:按字母序输出[/b]
HLW

HWL

LHW

LWH

WHL

WLH

import java.util.Scanner;

import java.util.TreeSet;

public class Main {

 public static int count = 0;

 public static void main(String[] args){   

  Scanner scan = new Scanner(System.in);

  while(scan.hasNext()){ 

   String key = scan.nextLine();   

   TreeSet<String> ts = new TreeSet<String>();

   QuanPaiLie(0 , key , ts);

   for(String keyStr : ts){

    System.out.println(keyStr);

   }

  }

  scan.close();

    }

 /**

  * 求字符串的全排列

  * 算法思想:递归

  */

 private static void QuanPaiLie(int step, String key , TreeSet<String> ts) {  

  int length = key.length(); 

  if(step == length - 1){   

   ts.add(key);

  }

  for(int i = step ; i < length ; i++){

   key = swap(step , i , key);  //交换 

   QuanPaiLie(step + 1 , key ,ts);

   key = swap(step , i , key);  //恢复

  }  

 }

 /**

  * 交换字符串中的某两位,返回新的字符串

  * */

    private static String swap(int a , int b , String str){

     //如果要交换的两个下标相等直接返回字符串

     if(a == b) return str;

     String result = "";

     int length = str.length();

     char[] strCh = str.toCharArray();

     char tempCh = strCh[a];

     strCh[a] = strCh[b];

     strCh[b] = tempCh;

     for(int i = 0 ; i < length ; i++){

      result += strCh[i];

     }

     return result;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java