黑马程序员技术交流社区
标题:
基础测试题——列出一个字符串的全字符组合情况
[打印本页]
作者:
王艳静
时间:
2015-8-13 19:19
标题:
基础测试题——列出一个字符串的全字符组合情况
请勿抄袭,仅供交流。这个是我的考试题答案共3种方法,大同小异。
但是最多只能排列长度为5的字符。此方法比较耗内存。
大家有没有更好的方法,欢迎交流
/**
* 5、 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符,例如:
* 原始字符串是"abc",打印得到下列所有组合情况:
* "a" "b" "c"
* "ab" "bc" "ca" "ba" "cb" "ac"
* "abc" "acb" "bac" "bca" "cab" "cba"
*
* @author 王艳静
*/
public class Test05 {
//定义类成员变量,方便类中方法调用
String str = "abc",s;
public static void main(String[] args) {
//创建对象,方便获取类中的方法和变量
Test05 test = new Test05();
//经测试,由于内存有限,只能排列长度小于6的字符串
if(test.str.length()<6){
System.out.println("第一种方法组合结果");
test.show(0,new String());
System.out.println("\r\n第二种方法组合结果");
test.show(0,new String(),test.str);
}
//此方法要求字符串长度为3
if(test.str.length()==3){
System.out.println("\r\n第三种方法组合结果");
test.show0();
}
}
/* 第一种方法,迭代法。
* 参数: level为计算迭代次数,初始值为0;
* temp为程序上一次迭代输出的字符串,初始值为空字符串;
* stemp为原始字符串减去temp剩余的字符串,初始值为原始字符串
* 思路:temp从空字符串开始,每迭代一次stemp给temp一个字符,
* 并用for循环遍历stemp中所有字符,打印所有可能,并作为参数传入下一次迭代
*
* */
public void show(int level,String temp,String stemp){
if(level<str.length()){
for (int i = 0; i < stemp.length(); i++) {
//元素转移过程
s=stemp.substring(i, i + 1);
String tm = new String(temp + s);
String stm = new String(stemp.substring(0,i)+stemp.substring(i+1,stemp.length()));
System.out.print(tm+" ");
show(level+1,tm,stm);
}
}
}
/* 第二种方法,迭代法。与第一种思想大体一致
* 传入参数level为计算迭代次数,初始值为0;temp为程序上一次迭代输出的字符串,初始值为空字符串
* 思路:temp从空字符串开始,每迭代一次往temp中添加一个temp中没有的字符(用contains(String str)来判断),
* 用for循环遍历所有字符,打印所有可能,并作为参数传入下一次迭代
*
* */
public void show(int level,String temp){
//限制迭代次数,为字符串的长度
if(level<str.length()){
//在一次迭代中需遍历字符串的每个字符
for (int i = 0; i < str.length(); i++) {
//获取单个字符定义为字符串(因为使用此方法contains(String str))
s=str.substring(i, i + 1);
if(!(temp.contains(s))){
String ss = new String(temp + s);
System.out.print(ss+" ");
show(level+1,ss);
}
}
}
}
//第三种方法,为第一,二种方法提供思路。只能用作3个字符的排列,不具备通用性
public void show0(){
char a,b,c;
for (int i = 0; i < str.length(); i++) {
a = str.charAt(i);
System.out.print(str.charAt(i)+" ");
for (int j = 0; j < str.length(); j++) {
b = str.charAt(j);
if(a != b){
System.out.print(""+a+b+" ");
for (int r = 0; r < str.length(); r++) {
c = str.charAt(r);
if((b!=c)&&(c!=a))
System.out.print(""+a+b+c+" ");
}
}
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2