牛客网刷题
牛客网刷题
问题描述:
给你一个字符串类型的数组arr,譬如: String[] arr = { “b\cst”, “d\”, “a\d\e”, “a\b\c” }; 你把这些路径中蕴含的目录结构给画出来,子目录直接列在父目录下面,并比父目录 向右进两格,就像这样:
a
口口b
口口口口c
口口d
口口口口e
b
口口cst
d
同一级的需要按字母顺序排列,不能乱。
解题思路:该题型其实是一个前缀树的一种变化,将所给的字符串对应树的路径,同时将树的节点作为字符串数据,以便识别。
具体实现的思路图:
对应第一层的数据不需要输入空格(为了方便看将口代替空格),第二层对应输入两个口口…依次对应i层,即2i个口口。
实现代码:
//结构体
public static class Node {
public String name;
public TreeMap<String, Node> nextMap;
public Node(String name) {
this.name = name;
nextMap = new TreeMap<>();
}
}
//打印数据
public static void print(String[] folderPaths) {
if (folderPaths == null || folderPaths.length == 0) {
return;
}
Node head = generateFolderTree(folderPaths);
printProcess(head, 0);
}
//前缀树的步骤
public static Node generateFolderTree(String[] folderPaths) {
Node head = new Node("");
for (String foldPath : folderPaths) {
String[] paths = foldPath.split("\\\\");
Node cur = head;
for (int i = 0; i < paths.length; i++) {
if (!cur.nextMap.containsKey(paths[i])) {
cur.nextMap.put(paths[i], new Node(paths[i]));
}
cur = cur.nextMap.get(paths[i]);
}
}
return head;
}
public static void printProcess(Node head, int level) {
if (level != 0) {
System.out.println(get2nSpace(level) + head.name);
}
for (Node next : head.nextMap.values()) {
printProcess(next, level + 1);
}
}
public static String get2nSpace(int n) {
String res = "";
for (int i = 1; i < n; i++) {
res += " ";
}
return res;
}
这边需要注意的是 :java 语言的 对应" // ",实际输出是 " / ",由于Java语言,涉及转义。所以不同语言对应不同代码。