一、问题描述
功能描述:查找一个字符串的子字符串集 输入:abab 输出:a b ab ba aba bab
二、算法分析
/** * Gets the all the substring from input data string * @param data * @return */ public List<String> getChildren(String data) { List<String> list = new ArrayList<String>(); char[] arr = data.toCharArray(); int count = 1; while (count < data.length()) { for (int i = 0; i <= arr.length - count; i++) { if (count == 1) { if (!list.contains(String.valueOf(arr[i]))) { list.add(String.valueOf(arr[i])); } } else if (count == 2) { char[] temp = { arr[i], arr[i + 1] }; if (!list.contains(String.valueOf(temp))) { list.add(String.valueOf(temp)); } } else if (count == 3) { char[] temp = { arr[i], arr[i + 1], arr[i + 2] }; if (!list.contains(String.valueOf(temp))) { list.add(String.valueOf(temp)); } } } count++; } for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + " "); } System.out.println("-----------"); return list; }
算法二、(来自网友)
/** * Gets from online * @param str * @return */ public Set<String> getChildren1(String str) { Set<String> data = new TreeSet<String>(); int len = str.length(); for (int i = 1; i < len; i++) { for (int j = 0; j < str.length(); j++) { String tmp = str.substring(j); while (tmp.length() >= i) { data.add(tmp.substring(0, i)); tmp = tmp.substring(i); } } } for (String key : data) { System.out.print(key + " "); } return data; }三、测试
public static void main(String[] args) { Main19 m = new Main19(); m.getChildren("abab"); m.getChildren1("abab"); }
测试结果:
a b ab ba aba bab ----------- a ab aba b ba bab
感悟:看来网友的算法,发现更加高明,其一,利用set保证了所用的子串是唯一的,其三,利用动态二重循环保证了从1个到n-1个所有子串和substring方法。其三、更具有适用性,个人的仅仅适用于字符串长度为四。