日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[LeetCode]--71. Simplify Path

發布時間:2023/11/29 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode]--71. 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”.

這個題目重點就是要理解它的意思,如果是一個點 . 那就是當前路徑,不管,如果是兩個點 .. 那就是當前路徑的上一個目錄。這樣我們用棧來表示的話,就是如下所示

path:"/a/./b/../../c/"split:"a",".","b","..","..","c"stack:push(a), push(b), pop(b), pop(a), push(c) --> c

明白這個之后就一目了然了,就是注意返回的時候如果是”/”或者”/../”這種情形就行。

public String simplifyPath(String path) {String res = "";String[] arrs = path.split("/");Stack<String> s = new Stack<String>();for (int i = 0; i < arrs.length; i++) {if (arrs[i].equals("")) {continue;}if (!arrs[i].equals(".") && !arrs[i].equals("..")) {s.push(arrs[i]);}if (arrs[i].equals("..") && !s.isEmpty()) {s.pop();}}if (s.isEmpty())return "/";while (!s.isEmpty())res = "/" + s.pop() + res;return res;}

另一種鏈表的做法

public String simplifyPath1(String path) {String result = "/";String[] stubs = path.split("/+");ArrayList<String> paths = new ArrayList<String>();for (String s : stubs){if(s.equals("..")){if(paths.size() > 0){paths.remove(paths.size() - 1);}}else if (!s.equals(".") && !s.equals("")){paths.add(s);}}for (String s : paths){result += s + "/";}if (result.length() > 1)result = result.substring(0, result.length() - 1); return result;}

總結

以上是生活随笔為你收集整理的[LeetCode]--71. Simplify Path的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。