[leetcode]Simplify Path

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   strong   io   art   

Simplify Path

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".

演算法思路:

棧。設定兩指標,根據‘/’分割出一個一個的路徑名,壓棧。pop的時候,遇到‘.’和“”(//生產的)不用管,".."復原,並記錄復原次數。

注意:當路徑為空白時,要返回 / 。

吐槽:有一個奇葩case -> /... 後來才反映過來,人家的路徑名叫...搞笑嗎?

 1 public class Solution { 2     public String simplifyPath(String path) { 3         if(path == null || path.length() == 0) return ""; 4         int start = 0; 5         Stack<String> stack = new Stack<String>(); 6         for(int i = 1; i < path.length(); i++){ 7             if(path.charAt(i) == ‘/‘ || i == path.length() - 1){ 8                    String s = (path.charAt(i) == ‘/‘) ? path.substring(start + 1, i) : path.substring(start + 1, i + 1); 9                    stack.push(s);10                    start = i;11             }12         }13         StringBuilder sb = new StringBuilder();14         int traceBack = 0;15         while(!stack.isEmpty()){16             String str = stack.pop();17             if(".".equals(str) || str.length() == 0)continue;18             else if("..".equals(str)) {19                 traceBack++;20             }else{21                 traceBack--;22                 if(traceBack < 0){23                     sb.insert(0,  "/" + str);24                     traceBack = 0;25                 }26             }27         }28         return sb.toString().length() == 0 ? "/" : sb.toString();29     }30 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.