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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/72713.html
摘要:標題文字簡化風格的絕對路徑。我們可以首先將所有的內容從中分離出來,然后分別處理。這里我們需要用到堆棧的數據結構。堆棧有很多種實現方式,中的類類都可以實現其功能。我們將讀到的路徑入棧,根據操作符出棧,最后將棧中剩余的元素組織成路徑返回即可。 標題文字 Given an absolute path for a file (Unix-style), simplify it. For exa...
摘要:題目解答的規則如下三種需要跳過的情況當遇到時,需要向前進出來的順序是反的,所以加的時候,把最新出來的路徑加在前面 題目:Given an absolute path for a file (Unix-style), simplify it. For example,path = /home/, => /homepath = /a/./b/../../c/, => /cclick to ...
摘要:棧法復雜度時間空間思路思路很簡單,先將整個路徑按照分開來,然后用一個棧,遇到時彈出一個,遇到和空字符串則不變,遇到正常路徑則壓入棧中。注意如果結果為空,要返回一個彈出棧時要先檢查棧是否為空代碼 Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example, path = /...
摘要:題目給定一個文檔的完全路徑,請進行路徑簡化。例如,邊界情況你是否考慮了路徑的情況在這種情況下,你需返回。此外,路徑中也可能包含多個斜杠,如。文化和社會被恐懼所塑造,在將來這無疑也不會消失。 題目 給定一個文檔 (Unix-style) 的完全路徑,請進行路徑簡化。 例如,path = /home/, => /homepath = /a/./b/../../c/, => /c 邊界情況:...
摘要:題目給定一個文檔的完全路徑,請進行路徑簡化。例如,邊界情況你是否考慮了路徑的情況在這種情況下,你需返回。此外,路徑中也可能包含多個斜杠,如。文化和社會被恐懼所塑造,在將來這無疑也不會消失。 題目 給定一個文檔 (Unix-style) 的完全路徑,請進行路徑簡化。 例如,path = /home/, => /homepath = /a/./b/../../c/, => /c 邊界情況:...
閱讀 3595·2023-04-26 02:55
閱讀 2865·2021-11-02 14:38
閱讀 4144·2021-10-21 09:39
閱讀 2853·2021-09-27 13:36
閱讀 3960·2021-09-22 15:08
閱讀 2655·2021-09-08 10:42
閱讀 2810·2019-08-29 12:21
閱讀 677·2019-08-29 11:22