黑马程序员____字符串消重复求所有非空子串

----------------------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 getSubSequences(String strings) {
		ArrayList list = new ArrayList();
		doGetSubSequences(strings, "", list);
		//消除空字符串
		list.remove("");
		//对集合进行排序
		Collections.sort(list);
		return list;
	}
	//获取字符串的所有子集含空集和自身
	private static void doGetSubSequences(String strings, String splits, 
			ArrayList 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培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima


你可能感兴趣的:(程序设计)