1. 程式人生 > >71. Simplify Path

71. Simplify Path

實現 push 需要 sta ash 裏的 light als brush

https://leetcode.com/problems/simplify-path/#/description

難度:85,雖然不難,但是裏面關於LinkedList實現的棧的各種技巧的使用,還是有比較高要求的。

先用了String[] split (String regex)這個函數。先把輸入字符串以‘/‘為分隔符分來,如果遇到‘.‘或者空輸入什麽都不做。如果遇到‘..‘就彈棧。其他情況則將對應元素入棧。這樣,棧裏面存的就是最後簡化的路徑,我們只需把棧裏面的元素按從末尾到棧頂的順序取出來,之間添加“/”就可以了。

這裏要取棧底元素,用的方法是:stack.removeLast();

還有就是寫的時候,忽視了String是一個object, ‘==’表示內存地址都一樣的情況,equals才是僅僅值相同的情況

split函數的用法:The string "boo:and:foo", for example, split(":")的結果是 {“boo”, "and", "foo"}; 需要註意的是:Trailing empty strings are not included in the resulting array.比如,split("o")的結果是{“b”, "", ":and:f"}

註意最後是如何順序寫出Stack裏的元素

public String simplifyPath(String path) {
    Deque<String> stack = new LinkedList<>();
    Set<String> skip = new HashSet<>(Arrays.asList("..",".",""));  //new HashSet<>(Arrays.asList("..", ".", ""))---
                                      生成list放到hashset中,為了以後跳過 for (String dir : path.split("/")) { if (dir.equals("..") && !stack.isEmpty()) stack.pop(); else if (!skip.contains(dir)) stack.push(dir); //stack只push非符號項的方法 } String res = ""; for (String dir : stack) res = "/" + dir + res; // .是如何生成/home/foo的, 為何想到用棧 return res.isEmpty() ? "/" : res; // 判斷是否為空的情況 }

  

71. Simplify Path