码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现字符串的全排列

时间:2014-09-01 22:53:04      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:全排列

package com.leetcode;

import java.util.ArrayList;

public class Permutation {
	
	public static void main(String[] args) {
		ArrayList<String> res = perms2("abc");
		System.out.println(res);
	}
	
	//法一:
	public static ArrayList<String> perms1(String s){
		ArrayList<String> res = new ArrayList<String>();
		if(s == null)
			return null;
		if(s.isEmpty()){
			res.add("");
			return res;
		}
		for(int i = 0; i < s.length(); i++){
			char c = s.charAt(i);
			String start = s.substring(0, i);
			String end = s.substring(i + 1);
			ArrayList<String> words = perms1(start + end);
			for(String word : words){
				String newStr = c + word;
				res.add(newStr);
			}
		}
		return res;
	}
	
	//法二:
	public static ArrayList<String> perms2(String s){
		ArrayList<String> res = new ArrayList<String>();
		if(s == null)
			return null;
		if(s.isEmpty()){
			res.add("");
			return res;
		}
		char c = s.charAt(0);
		String reminder = s.substring(1);
		ArrayList<String> words = perms2(reminder);
		for(String word : words){
			for(int i = 0; i <= word.length(); i++){
				String newStr = insertCharAt(word, c, i);
				res.add(newStr);
			}
		}
		return res;
	}
	
	public static String insertCharAt(String s, char c, int i){
		String start = s.substring(0, i);
		String end = s.substring(i);
		return start + c + end;
	}
}

Java实现字符串的全排列

标签:全排列

原文地址:http://blog.csdn.net/hjiam2/article/details/38986151

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!