自己写的JAVA组合排列类

给出需要组合的字符串,最小长度,最大长度

算出所有不重复的组合

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Weave {
 private BufferedReader in;
 private InputStreamReader is;
 private char[] chars;
 private int charLen;
 int min;
 int max;
 int count = 0;
 
 public Weave(){
  open();
  String str = getStrInput("请输入需要组合的字符穿:");
  chars = str.toCharArray();
  charLen = chars.length;
  min = getIntInput("请输入需要组合的最小长度:");
  max = getIntInput("请输入需要组合的最大长度:");
  close();
 }
 
 public static void main(String[] args)   {
  
  Weave weave = new Weave();
  long begin=System.currentTimeMillis();
  weave.combination();
  weave.loger("执行时间:"+(System.currentTimeMillis() - begin)+"毫秒");
   }
 
 public void combination(){
  count = 0;
  if (min>max){
      int t = max;
      max = min;
      min = t;
     }
     for (int i= min;i<=max;i++){
      combination(new StringBuffer(""),i);
  }
 }
 
 
 public void combination(StringBuffer  str,int length) {
  
  if (length < 1){
   loger("长度小于1");
  }

  if (length == 1){
   for(int i=0;i<charLen;i++){
    StringBuffer result = new StringBuffer(str);
    result.append(chars[i]);
    //根据组合的结果执行某些操作
                doSome(result);
   }
  }

  if (length > 1) {
   for(int i=0;i<charLen;i++){
    StringBuffer temp = new StringBuffer(str);
    combination(temp.append(chars[i]),length-1);
   }
  }
 }
 
 public void doSome(StringBuffer str){
  count++;
  loger(count + ".  " +str);
 }
 
 public int getIntInput(String info) {
        int temp=0;
        loger("\n"+info);
        try {
            temp=Integer.parseInt(in.readLine());
        }
        catch(Exception e) {
         loger("错误!!请从新输入");
            return getIntInput(info);
        }
        if(temp<=0) {
         loger("\n错误!!必须大于0!");
            return getIntInput("从新输入 : ");
        }
       
        return temp;       
    }
 
 public String getStrInput(String info) {
        loger("\n"+info);
        String temp = "";
        try {
   temp = in.readLine();
  } catch (IOException e) {
   loger(e);
  }
        if(null == temp || "".equals(temp)) {
         loger("\n错误!!不能输入空字符串!");
            return getStrInput("从新输入 : ");
        }
        return temp;       
    }
 
 /**
  * 反馈信息
  * @param o
  */
 public void loger(Object o){
  System.out.println(o.toString());
 }
 
 public void close(){
  try {
   is.close();
   in.close();
  } catch (IOException e) {
   loger(e);
  }
  
 }
 
 public void open(){
  is = new InputStreamReader(System.in);
  in=new BufferedReader(is);
 }

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值