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 cancelled out, a is cancelled out path = "/a//b////c/d//././/..", => "/a/b/c" //here d is cancelled out
In a UNIX-style file system, a period (".") refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki...
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".
class Solution { public String simplifyPath(String path) { Dequestack = new ArrayDeque<>(); Set ignore = new HashSet<>(Arrays.asList("", ".", "..")); for (String dir: path.split("/")) { if (!stack.isEmpty() && dir.equals("..")) stack.pop(); if (!ignore.contains(dir)) stack.push(dir); } String res = ""; while (!stack.isEmpty()) { res = "/"+stack.pop()+res; } if (res.equals("")) return "/"; return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/72713.html
摘要:標(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...
摘要:題目解答的規(guī)則如下三種需要跳過的情況當(dāng)遇到時,需要向前進(jìn)出來的順序是反的,所以加的時候,把最新出來的路徑加在前面 題目:Given an absolute path for a file (Unix-style), simplify it. For example,path = /home/, => /homepath = /a/./b/../../c/, => /cclick to ...
摘要:棧法復(fù)雜度時間空間思路思路很簡單,先將整個路徑按照分開來,然后用一個棧,遇到時彈出一個,遇到和空字符串則不變,遇到正常路徑則壓入棧中。注意如果結(jié)果為空,要返回一個彈出棧時要先檢查棧是否為空代碼 Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example, path = /...
摘要:題目給定一個文檔的完全路徑,請進(jìn)行路徑簡化。例如,邊界情況你是否考慮了路徑的情況在這種情況下,你需返回。此外,路徑中也可能包含多個斜杠,如。文化和社會被恐懼所塑造,在將來這無疑也不會消失。 題目 給定一個文檔 (Unix-style) 的完全路徑,請進(jìn)行路徑簡化。 例如,path = /home/, => /homepath = /a/./b/../../c/, => /c 邊界情況:...
摘要:題目給定一個文檔的完全路徑,請進(jìn)行路徑簡化。例如,邊界情況你是否考慮了路徑的情況在這種情況下,你需返回。此外,路徑中也可能包含多個斜杠,如。文化和社會被恐懼所塑造,在將來這無疑也不會消失。 題目 給定一個文檔 (Unix-style) 的完全路徑,請進(jìn)行路徑簡化。 例如,path = /home/, => /homepath = /a/./b/../../c/, => /c 邊界情況:...
閱讀 3593·2023-04-26 02:55
閱讀 2863·2021-11-02 14:38
閱讀 4139·2021-10-21 09:39
閱讀 2849·2021-09-27 13:36
閱讀 3951·2021-09-22 15:08
閱讀 2649·2021-09-08 10:42
閱讀 2807·2019-08-29 12:21
閱讀 673·2019-08-29 11:22