import java.util.List; import java.util.ArrayList; /** * 求字符串的len组合数 * * @author wenin819 * */ public class Combination{ /** * 求组合数的主要方法 */ public static List<String> combination(String inStr, int len){ StringBuffer noDoubleStr =new StringBuffer(inStr); noDouble(noDoubleStr); if( len >= noDoubleStr.length()) return null; return combinationItem(noDoubleStr , len); } /** * 去除重复的字符 */ public static void noDouble(StringBuffer input){ for(int i = 0; i < input.length(); i++){ char temp = input.charAt(i); for(int j = i+1; j < input.length(); ){ if(temp == input.charAt(j)){ input.deleteCharAt(j); }else{ j++; } } } } /** * 求组合数 */ public static List<String> combinationItem(StringBuffer input, int len){ List<String> rsList = new ArrayList<String>(); boolean[] array = new boolean[input.length()]; for(int i = 0; i < array.length; i++){ array[i] = false; } do{ if(len == countOfTrue(array)){ StringBuffer temp = new StringBuffer(input); for(int j = temp.length() - 1;j >= 0;j--){ if(array[j]) continue; temp.deleteCharAt(j); } rsList.add(new String(temp)); } }while(booleanAdd(array)); return rsList; } /** * 求boolean数组元素为true的个数 */ public static int countOfTrue(boolean[] array){ int count = 0; for(int i = 0;i < array.length;i++){ if(array[i]) count++; } return count; } /** * boolean数组自加(同2进制加1) */ public static boolean booleanAdd(boolean[] array){ boolean flag = true; for(int i = 0;i < array.length; i++){ if(false == flag) return true; if(array.length-1 == i && true == array[i]){ array[i] = false; return false; } if(false == array[i]){ array[i] = true; return true; } array[i] = false; } return false; } public static void main(String[] args){ String input = new String("abcde"); int len = 3; if(args.length > 1){ input = args[0]; len = Integer.parseInt(args[1]); } List list = combination(input,len); if(list != null){ System.out.println(input+"的"+len+"组合数的个数为:"+list.size()+"/n组合数分别为:"); for(int i = 0; i < list.size(); i++){ System.out.println(i+1+": "+list.get(i).toString()); } } } }
相关文章
- 05-02求字符串的len组合数(java程序)
- 05-02求字符串全排列的递归算法(java程序)