題目1090:路徑列印。N叉樹

來源:互聯網
上載者:User
題目描述:

給你一串路徑,譬如:
a\b\c
a\d\e
b\cst
d\
你把這些路徑中蘊含的目錄結構給畫出來,子目錄直接列在父目錄下面,並比父目錄向右縮一格,就像這樣:
a
  b
    c
  d  
    e
b
  cst
d
同一級的需要按字母順序排列,不能亂。

輸入:

    每個測試案例第一行為一個正整數n(n<=10)表示有n個路徑,當n為0時,測試結束,接下來有n行,每行有一個字串表示一個路徑,長度小於50。

輸出:

輸出目錄結構,每一個測試範例的輸出緊跟一個空行。

範例輸入:
4a\b\ca\d\eb\cstd\0
範例輸出:
a  b    c  d    eb  cstd

我在這裡是是建了一個多叉樹。兄弟節點之間是排序的。

自訂一個跟節點。每個節點都一個首碼(subString),代表他們的路徑,如果相同,則是同一個目錄。

是用Java的TreeSet可以自動排序。

解釋在代碼注釋裡了。

網上也有用字典樹的。還有一種簡單的方法是a/b/c, 可以看成是檔案 a,a/b,a/b/c 這樣把所有的檔案按照自訂規則排序,在輸出就行了。

public class PathPrint_1090 {static int n;static Node root; //定義一個根節點public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNextInt()) {n = scanner.nextInt();if(n == 0)break;String str;Node root = new Node();root.key = "";root.subString = "";root.children = new TreeSet<Node>();for (int i = 0; i < n; i++) {str = scanner.next();root.addChild(new Node(str.split("\\\\"), 0, root)); //將讀入的一個字串分割為一個字元數組,構造一個鏈表}root.print();System.out.println();}}}class Node implements Comparable<Node> {public String key; //需要輸出的名稱public String subString; //首碼,相同則為一個目錄public TreeSet<Node> children; //子節點。個數不定public Node father; //父節點public int pre; //代表位移量public int compareTo(Node o) { //定義比較函數。即比較首碼 a\b\ == a\b\, 是一個目錄return this.subString.compareTo(o.subString);}public Node() {}//根據一個字元數組,構造一個節點串. public Node(String str[], int index, Node f) {this.subString = "";if (index == str.length) //到了最後就直接返回return;for (int i = 1; i <= index; i++)this.subString += str[i] + '\\'; //獲得首碼if (index == 0)this.subString = str[0];this.key = str[index];this.pre = f.pre + f.key.length() + 1; //位移量等於父節點的位移量 + 父節點長度this.father = f;if (index != str.length) {if (this.children == null)this.children = new TreeSet<Node>();children.add(new Node(str, index + 1, this));}}public void addChild(Node n) {  //添加一個孩子節點//由於孩子節點可能重複,重新合并if (children.contains(n)) {Node temp = null;for (Node temp2 : children) {if (temp2.compareTo(n) == 0)temp = temp2;}temp.addChild(n.children.first());} else {children.add(n);}}public void print() {if (this.key == null)return;if(this.key != ""){pre--; //由於第一個位置會多個空格while (pre-- > 0)System.out.print(" ");System.out.println(key);}if (this.children != null && children.size() > 0) {for (Node n : children)n.print();}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.