1. 程式人生 > >黑馬程式設計師____字串消重複求所有非空子串

黑馬程式設計師____字串消重複求所有非空子串

----------------------android培訓java培訓、期待與您交流! ----------------------

/*
題目:使用者給一個字串例如"abcc",對此字串消重,後求所有子串(例如本題的解是a/b/c/ab/ac/ba/ca/bc/cb/abc/...)
*/
import java.util.*;
class GetSubStr
{	
	public static void main(String [] args)
	{		
		System.out.println(getSubSequences(eliminatingDuplicate()));
	}
	//正則表示式給字串消重複
	public static String eliminatingDuplicate()
	{
		String str = "abcc";
		str = str.replaceAll("(.)\\1+","$1");
		return str;
	}
	//獲取字串的所有非空子串
	public static ArrayList<String> getSubSequences(String strings) {
		ArrayList<String> list = new ArrayList<String>();
		doGetSubSequences(strings, "", list);
		//消除空字串
		list.remove("");
		//對集合進行排序
		Collections.sort(list);
		return list;
	}
	//獲取字串的所有子集含空集和自身
	private static void doGetSubSequences(String strings, String splits, 
			ArrayList<String> list) {
		if (strings.length() == 0) {
			list.add(splits);
			return;
		}		
		String tail = strings.substring(1);
		doGetSubSequences(tail, splits, list);
		doGetSubSequences(tail, splits + strings.charAt(0), list);
	}
}

執行結果:

---------------------- android培訓java培訓、期待與您交流! ----------------------