将点分隔字符串分组为固定格式
在输入中,我得到了代表某种树结构的下一行的数组:
"323-060",
"323-060.040",
"323-060.040.030",
"323-060.088",
"323-060.088.020",
"323-060.010",
"323-060.010.080",
"323-060.010.080.020",
"323-060.010.080.060"
它是树形结构:
“323-060”-根 这棵树有下一个层次结构
323-060 /*rot*/
040 /*second level, full path: 323-060.040*/
030 /* third level, full path: 323-060.040.303 */
088
020
因此,我必须将下一个列表分组:
"323-060\323-060.040\323-060.040.030"
"323-060\323-060.088\323-060.088.020"
"323-060\323-060.010\323-060.010.080\323-060.010.080.020"
"323-060\323-060.010\323-060.010.080\323-060.010.080.060"
如何在 Java 中做到这一点?
在下面的代码中,
Node
类代表树中的每个node
。 buildTree()
方法通过用点分割每个字符串来获取部分来根据输入创建树。 HashMap
用于通过完整路径跟踪 nodes
。对于每一部分,我们检查 node
是否存在于地图中,如果不存在,我们创建一个新的。在 generatePaths()
方法中,我们递归遍历树以创建预期输出。
package org.example;
import java.util.*;
public class GroupString {
static class Node {
String value;
List<Node> children;
Node(String value) {
this.value = value;
this.children = new ArrayList<>();
}
}
public static void main(String[] args) {
String[] input = {
"323-060",
"323-060.040",
"323-060.040.030",
"323-060.088",
"323-060.088.020",
"323-060.010",
"323-060.010.080",
"323-060.010.080.020",
"323-060.010.080.060"
};
Node root = buildTree(input);
List<String> result = new ArrayList<>();
generatePaths(root, new ArrayList<>(), result);
for (String path : result) {
System.out.println(path);
}
}
private static Node buildTree(String[] input) {
Map<String, Node> nodeMap = new HashMap<>();
Node root = null;
for (String path : input) {
String[] parts = path.split("\\.");
StringBuilder currentPath = new StringBuilder();
Node parent = null;
for (String part : parts) {
if (currentPath.length() > 0) {
currentPath.append(".");
}
currentPath.append(part);
String key = currentPath.toString();
Node currentNode = nodeMap.getOrDefault(key, new Node(key));
nodeMap.putIfAbsent(key, currentNode);
if (parent != null) {
if (!parent.children.contains(currentNode)) {
parent.children.add(currentNode);
}
} else {
root = currentNode;
}
parent = currentNode;
}
}
return root;
}
private static void generatePaths(Node node, List<String> path, List<String> result) {
if (node == null) return;
path.add(node.value);
if (node.children.isEmpty()) {
result.add(String.join("\\", path));
} else {
for (Node child : node.children) {
generatePaths(child, new ArrayList<>(path), result);
}
}
}
}