该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
这是我做的,本来想用hashtable的,但是无序,所以考虑用了TreeMap.不过好在做了出来。
=======================================================================
package Interview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class D1 {
public static void subString(String str){
//TreeMap支持key字典排序,但是由于先要数字排序,所以又定义了ans
TreeMap res = new TreeMap();
TreeMap> ans = new TreeMap>();
//处理特殊情况
if(str==""||str==null){
return;
}
if(str.length()==1){
res.put(str, 1);
}else{
String temp = null;
for (int i = 0; i < str.length()-2;i++) {
temp = str.substring(i, i+1);
judgeExist(temp,res);
temp = str.substring(i, i+2);
judgeExist(temp,res);
temp = str.substring(i, i+3);
judgeExist(temp,res);
}
temp = str.substring(str.length()-2,str.length()-1);
judgeExist(temp,res);
temp = str.substring(str.length()-1,str.length());
judgeExist(temp,res);
temp = str.substring(str.length()-2,str.length());
judgeExist(temp,res);
}
sort(res, ans);
print(ans);
}
//判断key值是否存在
public static void judgeExist(String str,TreeMap res){
if(!res.containsKey(str)){
res.put(str, 1);
}else{
Integer newValue = res.get(str);
newValue++;
res.put(str, newValue);
}
}
//descendingKeySet逆序打印
public static void print(TreeMap> map){
Set set = map.descendingKeySet();
Iterator ite = set.iterator ();
while(ite.hasNext ()){
Integer key = ite.next();
ArrayList arr = map.get(key);
for (String string : arr) {
System.out.println(string+"\t"+key);
}
}
}
//将出现次数作为key值,key值相同的加入同一个集合中
public static void sort(TreeMap res,TreeMap> ans){
Set set = res.keySet ();//
Iterator ite = set.iterator ();
while(ite.hasNext ()){
String key = ite.next();
Integer val = res.get(key);
if(!ans.containsKey(val)){
ArrayList arr = new ArrayList();
arr.add(key);
ans.put(val,arr);
}else{
ArrayList arr = ans.get(val);
arr.add(key);
}
}
}
public static void main(String[] args) {
subString("abcdefg");
}
}