字符串字母全排列练习


输入例子:
WHL


输出例子:按字母序输出
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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值