`
yyang900427
  • 浏览: 11247 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

字符串的组合

阅读更多

/**
 * 题目:输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入
 * abc,它的组合有a、b、c、ab、ac、bc、abc。
 */

public class Launch
{
	public static void main(String ...args)
	{
		combination("abcd");	
	}

	public static void combination(String str)
	{
		int strLength;

		strLength = str.length();
		tmpArray = new char[strLength];

		for(int len = 1; len <= strLength; ++len)
		{
			tlen = len;
			getCombination(str, 0, len);
		}
	}

	private static void getCombination(String str, int index, int n)
	{
		int strLength = str.length();
	
		if(n == 0)
		{
			for(int i = tlen - 1; i >= 0; --i)
			{
				System.out.print(tmpArray[i]);
			}
			System.out.print(" ");
		}
		else
		{
			for(int i = index; i < strLength; ++i)
			{
				if(strLength - index < n)
					break ;

				tmpArray[n - 1] = str.charAt(i);
				getCombination(str, i + 1, n - 1);
			}
		}
	}

	private static int tlen;
	private static char tmpArray[];
}

运行结果: a b c d ab ac ad bc bd cd abc abd acd bcd abcd 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics