posts - 495,comments - 227,trackbacks - 0
package com.test;

import java.util.ArrayList;
import java.util.List;

/**
 * 1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列, 如:512234、412345等.要求:"4"不能在第三位,"3"与"5"不能相连.
 * 
 * 
@author SIMONE wangxinsh55@126.com 2009-6-12
 
*/
public class GroupTest {
    
public static List<String> list = new ArrayList<String>();

    
/**
     * 构造字符串的所有排序组合
     * 
     * 
@param str 将要组合成的字符
     * 
@param nstr 源字符串集
     
*/
    
public static void group(String str, String nstr) {
        
if (str.length() != nstr.length()) {
            String rest 
= getRest(str, nstr);
            
for (int i = 0; i < rest.length(); i++) {
                String temp 
= str + rest.substring(i, i + 1);
                
if (temp.indexOf("4"!= 2 && temp.indexOf("35"== -1 && temp.indexOf("53"== -1) {// 过滤显示条件,如果去掉此处的判断,就是列出所有字符集的排列组合
                    System.out.println(temp);
                    
if (!list.contains(temp)) {
                        list.add(temp);
                    }
                    group(temp, nstr);
                }
            }
        }
    }

    
/**
     * 从源字符串集中去除将要组合成的字符
     * 
     * 
@param str 将要组合成的字符
     * 
@param nstr 源字符串集
     * 
@return 剩余字符串集
     
*/
    
public static String getRest(String str, String nstr) {
        String rest 
= "";
        
if (nstr.length() > str.length()) {
            rest 
= nstr;
            
for (int i = 0; i < str.length(); i++) {
                rest 
= rest.replaceFirst(str.substring(i, i + 1), "");// 注意此处的replaceFirst,而不是replaceAll
            }
        }
        
return rest;
    }

    
public static void main(String[] args) {
        group(
"""122345");
        System.out.println(list.toString());
    }
}
posted on 2009-06-12 15:54 SIMONE 阅读(4196) 评论(2)  编辑  收藏 所属分类: JAVA

FeedBack:
# re: 1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列, 如:512234、412345等.要求:"4"不能在第三位,"3"与"5"不能相连.
2009-06-12 17:14 | Ken Wu
god...  回复  更多评论
  
# re: 1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列, 如:512234、412345等.要求:"4"不能在第三位,"3"与"5"不能相连.
2009-06-14 19:01 | 爱吃鱼头
用经典的排列算法,在输出时判断一下就可以了。
不明白为什么要用字符串操作呢。  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: