import java.util.Map; import java.util.HashMap; import java.util.ArrayList; public class Converter { public static void main(String[] args) { String[] test = {"A", "A\\B\\C\\D\\E", "A\\B\\M\\Y"}; for(String s : normalizePath(test)) System.out.print(s + ", "); System.out.println(); } /* Основной метод, возвращающий правильный массив. */ public static String[] normalizePath(String[] s) { Node root = makeTree(s); ArrayList<String> result = new ArrayList<String>(); for (Map.Entry<String, Node> e : root.getChildren().entrySet()) addToRes(result, e.getValue(), ""); return result.toArray(new String[result.size()]); } /* Вспомогательный метод для рекурсивного обхода дерева */ private static void addToRes(ArrayList<String> result, Node n, String parent) { String currentPath = parent.equals("") ? n.getVal() : parent + "\\" + n.getVal(); result.add(currentPath); for (Map.Entry<String, Node> e : n.getChildren().entrySet()) addToRes(result, e.getValue(), currentPath); } /* Создатель дерева */ private static Node makeTree(String[] s) { Node root = new Node(""); for (String path : s) { Node node = root; for (String name : path.split("\\\\")) { node = addVal(node, name); } } return root; } /* Вспомогательный метод создателя дерева */ private static Node addVal(Node node, String val) { if (node.getVal().equals(val)) return node; Map<String, Node> children = node.getChildren(); if (children.containsKey(val)) return children.get(val); Node newNode = new Node(val); children.put(val, newNode); return newNode; } /* Элемент дерева */ private static class Node { private Map<String, Node> children = new HashMap<String, Node>(); private String val; public Node(String val) {this.val = val;} public Map<String, Node> getChildren() {return children;} public String getVal() {return val;} } }
Result
A, A\B, A\B\C, A\B\C\D, A\B\C\D\E, A\B\M, A\B\M\Y,
A1andA1\BB1\CCC1, then in this case the elementA1\BB1will be missing. - Dmitry08