[LeetCode][Java] Simplify Path

來源:互聯網
上載者:User

標籤:leetcode   java   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".

題意:

給定一個絕對路徑(Unix-style),簡化它.

比如:

path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

個別情況:

     1. 你是否考慮過例子path = "/../"? 這時你需要返回 "/".

     2. 另外一種特別的情況是含有重複的‘/‘ ,比如"/home//foo/". 這時你需要返回重複的部分,返回"/home/foo".

演算法分析:

 *思路比較明確,就是維護一個棧,對於每一個塊(以/作為分界)進行分析,
 * 如果遇到..則表示要上一層,那麼就是進行出棧操作,
 * 如果遇到.則是停留當前,直接跳過,
 * 其他檔案路徑則直接進棧即可。
 * 最後根據棧中的內容轉換成路徑即可(這裡是把棧轉成數組,然後依次添加)。
 * 當對所有分割成的字串都處理完後,檢查第一個棧是否為空白,如果棧為空白,則證明沒有可以重建的目錄名,返回"/"即可。
 * 當第一個棧不為空白時,這時候我們需要還原path.所以這裡我應用了第二個棧,先將第一個棧元素彈出入棧到第二個棧,然後再利用第二個棧還原回初始path 

AC代碼:

public class Solution {    public String simplifyPath(String path)     {        if(path == null||path.length()==0)            return path;                Stack<String> stack = new Stack<String>();        String[] list = path.split("/");                for(int i=0; i<list.length; i++)        {            if(list[i].equals(".")||list[i].length()==0)//如果遇到.則是停留當前,直接跳過                continue;            else if(!list[i].equals(".."))//其他檔案路徑則直接進棧即可                stack.push(list[i]);            else            {                if(!stack.isEmpty())//如果遇到..則表示要上一層,那麼就是進行出棧操作                    stack.pop();            }        }                StringBuilder res = new StringBuilder();                Stack<String> temp = new Stack<String>();        while(!stack.isEmpty())              temp.push(stack.pop());//原始path是/a/b/c/,棧裡的順序是:a b c,如果依次彈棧還原的話是:/c/b/a(錯誤!),正確答案為:/a/b/c                while(!temp.isEmpty())            res.append("/"+temp.pop());                if(res.length()==0)//如果棧為空白,則證明沒有可以重建的目錄名,返回"/"即可            res.append("/");                return res.toString();    }}


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Simplify Path

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.