全排列(编程之美)

字符串全排列

public class Q {

	/**
	 * @param args
	 */
	static int count=0;
	public static void main(Strin<pre name="code" class="html">public class Q {

	/**
	 * @param args
	 */
	static int count = 0;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StringBuffer a = new StringBuffer("abdbefb");
		q(a, 0, a.length() - 1);
		System.out.println(count);
	}

	private static void q(StringBuffer a, int i, int j) {
		// TODO Auto-generated method stub
		if (i >= j) {

			System.out.println(a);
			// System.out.println();
			count++;
		} else {
			for (int k = i;k<= j; k++) {
				//if (a.charAt(k) != a.charAt(k + 1) ) {
				if(isSwap(a,i,k))
				{
					swap(a, i, k);
					q(a, i + 1, j);
					swap(a, i, k);
				}

			}
		}

	}

	static boolean isSwap(StringBuffer str,int begin,int end)  
	{  
	   for(int i=begin;i<end;i++)  
	    {  
	        if(str.charAt(begin)==str.charAt(end))  
	            return false;  
	    }  
	    return true;  
	  
	}  
	private static void swap(StringBuffer a, int i, int k) {
		// TODO Auto-generated method stub
		char temp = a.charAt(i);
		a.setCharAt(i, a.charAt(k));
		a.setCharAt(k, temp);

	}

}

字符串去重

public class Q {

	/**
	 * @param args
	 */
	static int count = 0;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StringBuffer a = new StringBuffer("abdbefb");
		q(a, 0, a.length() - 1);
		System.out.println(count);
	}

	private static void q(StringBuffer a, int i, int j) {
		// TODO Auto-generated method stub
		if (i >= j) {

			System.out.println(a);
			// System.out.println();
			count++;
		} else {
			for (int k = i;k<= j; k++) {
				//if (a.charAt(k) != a.charAt(k + 1) ) {
				if(isSwap(a,i,k))
				{
					swap(a, i, k);
					q(a, i + 1, j);
					swap(a, i, k);
				}

			}
		}

	}

	static boolean isSwap(StringBuffer str,int begin,int end)  
	{  
	   for(int i=begin;i<end;i++)  
	    {  
	        if(str.charAt(begin)==str.charAt(end))  
	            return false;  
	    }  
	    return true;  
	  
	}  
	private static void swap(StringBuffer a, int i, int k) {
		// TODO Auto-generated method stub
		char temp = a.charAt(i);
		a.setCharAt(i, a.charAt(k));
		a.setCharAt(k, temp);

	}

}

    原文作者:吕德路
    原文地址: https://blog.csdn.net/lv836735240/article/details/41415985
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞