字符串所有可能的排列 例如abcd等等 递归算法和排列组合知识结合

可以用在md5编码等

package test;

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

import com.eetrust.raf.core.utils.encrypt.SecureMD5;

/**
 * 
 * @author chenhui
 * 
 */
public class Test2 {

	private StringBuilder builder = null;
	private static String KEY = "abcdef";
	private static String DBPWD = "AzoAMg9rWj";

	/**
	 * @param str
	 *            字符串str中每个字符都不相同
	 * @return 字符串str所有可能的排列
	 */
	public List<String> doCompute(String str) {
		List<String> list = new ArrayList<String>();
		List<String> temp = null;
		if (str.length() == 1) {
			list.add(str);
			return list;
		} else {
			char ch = str.charAt(0);
			temp = doCompute(str.substring(1));
			for (int j = 0; j < temp.size(); j++) {
				String s = temp.get(j);
				builder = new StringBuilder(s.length() + 1);
				// 将ch分别放到s.length() + 1个位置
				for (int k = 0; k < s.length() + 1; k++) {
					builder.append(s.substring(0, k));
					builder.append(ch);
					builder.append(s.substring(k, s.length()));
					list.add(j, builder.toString());
					builder.delete(0, s.length() + 1);
				}
			}
			for (int i = 0; i < temp.size(); i++) {
				temp.remove(i);
			}
			temp = null;
			return list;
		}
	}
	
	private static boolean vString(String str){
		//System.out.println("验证过:" + str);
		return SecureMD5.passDecrypt(DBPWD,KEY).equals(str);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Test2 abc = new Test2();
		long t1 = System.currentTimeMillis();
		List<String> list = abc.doCompute("89123");
		long t2 = System.currentTimeMillis();
		Collections.sort(list);
		long t3 = System.currentTimeMillis();
		for (String s : list) {
			if (vString(s)) {
				System.out.println("::" + s);
				return;
			}
		}
		System.out.println(t2 - t1);
		System.out.println(t3 - t2);
	}
}


你可能感兴趣的:(字符串所有可能的排列 例如abcd等等 递归算法和排列组合知识结合)