題目鏈接https://oj.leetcode.com/problems/simplify-path/
Description
Given an absolute path for a file (Unix-style), simplify it.
For example,
path?=?"/home/"=>?"/home"
path?=?"/a/./b/../../c/"=>?"/c"
Corner Cases:
Did you consider the case where?path?=?"/../"?In this case, you should return?"/".
Another corner case is the path might contain multiple slashes?'/'?together,
such as?"/home//foo/".In this case, you should ignore redundant slashes and return?"/home/foo".
算法思想
典型的字符串處理問題,先不想優(yōu)化的問題,先把邏輯結構和可能性理出來, 提示中已經給了兩種可能性,當然結合Unix的特性,可以得出一個流程圖,寫代碼之前劃了,弄上來挺麻煩的,就先這么著吧,有這么幾種可能性:(以/a/.b/../../c/為例)
1. 根目錄是/,到了根目錄..還是這個位置
2. 有文件名就能進入這個目錄,所以輸入a,得到的現(xiàn)在目錄為/a/
3. 一個點等于沒點,無效的,文件夾名中有點的情況需要再分析;
4. 非根目錄中..代表上一級目錄;
簡單一分析,你就看到了,這里做的是棧操作,后進先出,結果就是棧內元素。
AC代碼
https://oj.leetcode.com/submissions/detail/8709406/
關鍵詞
string, stack, regular