字符串字母全排列练习
2016-06-29 20:26
274 查看
[b]输入例子:[/b]
[b]输出例子:按字母序输出[/b]
import java.util.Scanner;
import java.util.TreeSet;
public class Main {
public static int count = 0;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String key = scan.nextLine();
TreeSet<String> ts = new TreeSet<String>();
QuanPaiLie(0 , key , ts);
for(String keyStr : ts){
System.out.println(keyStr);
}
}
scan.close();
}
/**
* 求字符串的全排列
* 算法思想:递归
*/
private static void QuanPaiLie(int step, String key , TreeSet<String> ts) {
int length = key.length();
if(step == length - 1){
ts.add(key);
}
for(int i = step ; i < length ; i++){
key = swap(step , i , key); //交换
QuanPaiLie(step + 1 , key ,ts);
key = swap(step , i , key); //恢复
}
}
/**
* 交换字符串中的某两位,返回新的字符串
* */
private static String swap(int a , int b , String str){
//如果要交换的两个下标相等直接返回字符串
if(a == b) return str;
String result = "";
int length = str.length();
char[] strCh = str.toCharArray();
char tempCh = strCh[a];
strCh[a] = strCh[b];
strCh[b] = tempCh;
for(int i = 0 ; i < length ; i++){
result += strCh[i];
}
return result;
}
}
[b]输入例子:[/b]
WHL
[b]输出例子:按字母序输出[/b]
HLW HWL LHW LWH WHL WLH
import java.util.Scanner;
import java.util.TreeSet;
public class Main {
public static int count = 0;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String key = scan.nextLine();
TreeSet<String> ts = new TreeSet<String>();
QuanPaiLie(0 , key , ts);
for(String keyStr : ts){
System.out.println(keyStr);
}
}
scan.close();
}
/**
* 求字符串的全排列
* 算法思想:递归
*/
private static void QuanPaiLie(int step, String key , TreeSet<String> ts) {
int length = key.length();
if(step == length - 1){
ts.add(key);
}
for(int i = step ; i < length ; i++){
key = swap(step , i , key); //交换
QuanPaiLie(step + 1 , key ,ts);
key = swap(step , i , key); //恢复
}
}
/**
* 交换字符串中的某两位,返回新的字符串
* */
private static String swap(int a , int b , String str){
//如果要交换的两个下标相等直接返回字符串
if(a == b) return str;
String result = "";
int length = str.length();
char[] strCh = str.toCharArray();
char tempCh = strCh[a];
strCh[a] = strCh[b];
strCh[b] = tempCh;
for(int i = 0 ; i < length ; i++){
result += strCh[i];
}
return result;
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树