摘要:題目解答的規(guī)則如下三種需要跳過的情況當(dāng)遇到時,需要向前進(jìn)出來的順序是反的,所以加的時候,把最新出來的路徑加在前面
題目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.
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".
解答:
unix style path的規(guī)則如下:
/ -> root
/a -> in (a)
. -> THIS dir path
/a/./ -> still in /a
/a/./b -> in /a/b
.. -> go "up" one level
/a/./b/.. -> /a/b/.. -> /a
/a/./b/../.. -> /a/.. -> /
/a/./b/../../c -> /c
public class Solution { public String simplifyPath(String path) { Stackstack = new Stack (); //三種需要跳過的情況 Set skip = new HashSet (Arrays.asList("..", ".", "")); for (String dir : path.split("/")) { //當(dāng)遇到..時,需要向前進(jìn) if (dir.equals("..") && !stack.isEmpty()) { stack.pop(); } else if (!skip.contains(dir)) { stack.push(dir); } } String result = ""; if (stack.isEmpty()) result += "/"; while (!stack.isEmpty()) { //pop出來的順序是反的,所以加的時候,把最新pop出來的路徑加在前面 result = "/" + stack.pop() + result; } return result; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/64974.html
Problem Given an absolute path for a file (Unix-style), simplify it. For example, path = /home/, => /home path = /a/./b/../../c/, => /c path = /a/../../b/../c//.//, => /c //here: b is cancelle...
摘要:標(biāo)題文字簡化風(fēng)格的絕對路徑。我們可以首先將所有的內(nèi)容從中分離出來,然后分別處理。這里我們需要用到堆棧的數(shù)據(jù)結(jié)構(gòu)。堆棧有很多種實(shí)現(xiàn)方式,中的類類都可以實(shí)現(xiàn)其功能。我們將讀到的路徑入棧,根據(jù)操作符出棧,最后將棧中剩余的元素組織成路徑返回即可。 標(biāo)題文字 Given an absolute path for a file (Unix-style), simplify it. For exa...
摘要:棧法復(fù)雜度時間空間思路思路很簡單,先將整個路徑按照分開來,然后用一個棧,遇到時彈出一個,遇到和空字符串則不變,遇到正常路徑則壓入棧中。注意如果結(jié)果為空,要返回一個彈出棧時要先檢查棧是否為空代碼 Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example, path = /...
摘要:,可以用函數(shù)去掉所有,然后多考慮一個中間為空的。關(guān)于語句的一個特點(diǎn)我們對和其實(shí)都是不做操作,然而,兩個可以都,但是不能都不做操作。像這樣這樣這兩個就都會等價于下一個就會出錯。 Problem Given an absolute path for a file (Unix-style), simplify it. Example /home/, => /home //去掉末尾的slash...
摘要:一前期準(zhǔn)備最新版本的安裝鏡像我所使用的是一個可以運(yùn)行的主機(jī)或虛擬機(jī)遠(yuǎn)程登錄客戶端我用的是二開始部署現(xiàn)在安裝基本都是圖形界面,這里我就不一一截圖了,我們直接進(jìn)入部署環(huán)節(jié)。 一、前期準(zhǔn)備: 最新版本的CentOS7.2 安裝鏡像(我所使用的是minimal) 一個可以運(yùn)行CentOS的主機(jī)或虛擬機(jī) SSH遠(yuǎn)程登錄客戶端(我用的是SecureCRT) 二、開始部署 現(xiàn)在Linux安裝基本...
閱讀 2901·2021-09-22 15:20
閱讀 2972·2021-09-22 15:19
閱讀 3479·2021-09-22 15:15
閱讀 2412·2021-09-08 09:35
閱讀 2387·2019-08-30 15:44
閱讀 3019·2019-08-30 10:50
閱讀 3752·2019-08-29 16:25
閱讀 1600·2019-08-26 13:55