Java面试题:输出字符串的所有组合

问题描述:假设字符串中所有的字符都不重复,输出字符串中的所有组合!

public class StringTestDemo {

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

		String s="abc";
		char[] c=s.toCharArray();
//		StringBuffer sb=new StringBuffer("");
//		int len=c.length;
//		for (int i = 0; i <= len; i++) {
//			CombineRecursiveImpl(c,0,i,sb);
//		}
		
		Combine(c);
	}

	private static void CombineRecursiveImpl(char[] c, int begin, int len,
			StringBuffer sb) {
		// TODO Auto-generated method stub
		if(len==0){
			System.out.println(sb+" ");
			return;
		}
		if(begin==c.length){
			return;
		}
		sb.append(c[begin]);
		CombineRecursiveImpl(c,begin+1,len-1,sb);
		sb.deleteCharAt(sb.length()-1);
		CombineRecursiveImpl(c,begin+1,len,sb);
	}
	
	public static void Combine(char[] c){
		if(c==null){
			return;
		}
		int len=c.length;
		boolean used[]=new boolean[len];
		char cache[]=new char[len];
		
		int result=len;
		
		while(true){
			int index=0;
			while(used[index]){
				used[index]=false;
				++result;
				if(++index==len){
					return;
				}
			}
			
			used[index]=true;
			cache[--result]=c[index];
			System.out.println(new String(cache).substring(result)+" ");
		}
	}

}


你可能感兴趣的:(Java面试题集)