//输入:{ ‘A’: 1, ‘B.A’: 2, ‘B.B’: 3, ‘CC.D.E’: 4, ‘CC.D.F’: 5}
//输出:{‘A’:1,‘CC’:{‘D’:{‘E’:4,‘F’:5}},‘B’:{‘A’:2,‘B’:3}}
思路是将其转化为树结构,然后按照规则打印树的信息
如有更好的建议请指正
import java.util.*;
public class Main4 {
//字典转化, { ‘A’: 1, ‘B.A’: 2, ‘B.B’: 3, ‘CC.D.E’: 4, ‘CC.D.F’: 5}.
static class TreeNode{
HashMap<String, TreeNode> children = new HashMap<>();
HashMap<String,String> attributes = new HashMap<>();
@Override
public String toString() {
String result = "{";
int attSize = attributes.size();
int childSize = children.size();
Iterator<Map.Entry<String,String>> atts = attributes.entrySet().iterator();
if(!children.isEmpty()){ //每位后面都加 “,”号
while (atts.hasNext()){
Map.Entry<String ,String> entry = atts.next();
result += "'" + entry.getKey() + "':" + entry.getValue() + ",";
}
}else{ //当到达最后一个属性且其后面没有子节点,其后面不加“,”号
int num = 1;
while (atts.hasNext()){
if(num != attSize){
Map.Entry<String ,String> entry = atts.next();
result += "'" + entry.getKey() + "':" + entry.getValue() + ",";
num++;
}else {
Map.Entry<String ,String> entry = atts.next();
result += "'" + entry.getKey() + "':" + entry.getValue();
}
}
}
Iterator<Map.Entry<String,TreeNode>> childs = children.entrySet().iterator();
int num = 1;
while (childs.hasNext()){
if(num != childSize){
Map.Entry<String, TreeNode> entry = childs.next();
result += "'" + entry.getKey() + "':";
result += entry.getValue().toString() + ",";
num++;
}else {
Map.Entry<String, TreeNode> entry = childs.next();
result += "'" + entry.getKey() + "':";
result += entry.getValue().toString();
}
}
result += "}";
return result;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //输入 :{ ‘A’: 1, ‘B.A’: 2, ‘B.B’: 3, ‘CC.D.E’: 4, ‘CC.D.F’: 5}
String s = scan.nextLine();
String ss = s.substring(2,s.length()-1).replaceAll(" ","");
String[] arr = ss.split(",");
TreeNode root = new TreeNode();
HashMap<String,String> attributes = root.attributes;
HashMap<String, TreeNode> children = root.children;
for(int i = 0; i < arr.length; i++){
String[] node = arr[i].split(":");
String key = node[0].substring(1,node[0].length()-1);
String value = node[1];
if(!arr[i].contains(".")){
attributes.put(key,value);
}else{
String[] list = key.split("\\.");
int len = list.length;
HashMap<String,TreeNode> temp = children;
TreeNode child = new TreeNode();
for(int j = 0; j < len-1; j++){ //逐级增加子节点
if(!temp.containsKey(list[j])){
child = new TreeNode();
temp.put(list[j], child);
temp = child.children;
}else {
child = temp.get(list[j]);
temp = child.children;
}
}
//最后放一个属性
child.attributes.put(list[len-1],value);
}
}
System.out.println(root.toString());
}
}