Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
- 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/"
, => "/a/c"和path =
"/a/./b/c/"
, => "/a/b/c",
這樣我們就可以知道中間是"."的情況直接去掉,是".."時刪掉它上面挨着的一個路徑,而下面的邊界條件給的一些情況中可以得知,如果是空的話返回"/",如果有多個"/"只保留一個。那么我們可以把路徑看做是由一個或多個"/"分割開的眾多子字符串,把它們分別提取出來一一處理即可,代碼如下:
C++ 解法一:
class Solution { public: string simplifyPath(string path) { vector<string> v; int i = 0; while (i < path.size()) { while (path[i] == '/' && i < path.size()) ++i; if (i == path.size()) break; int start = i; while (path[i] != '/' && i < path.size()) ++i; int end = i - 1; string s = path.substr(start, end - start + 1); if (s == "..") { if (!v.empty()) v.pop_back(); } else if (s != ".") { v.push_back(s); } } if (v.empty()) return "/"; string res; for (int i = 0; i < v.size(); ++i) { res += '/' + v[i]; } return res; } };
還有一種解法是利用了C語言中的函數strtok來分隔字符串,但是需要把string和char*類型相互轉換,轉換方法請猛戳這里。除了這塊不同,其余的思想和上面那種解法相同,代碼如下:
C 解法一:
class Solution { public: string simplifyPath(string path) { vector<string> v; char *cstr = new char[path.length() + 1]; strcpy(cstr, path.c_str()); char *pch = strtok(cstr, "/"); while (pch != NULL) { string p = string(pch); if (p == "..") { if (!v.empty()) v.pop_back(); } else if (p != ".") { v.push_back(p); } pch = strtok(NULL, "/"); } if (v.empty()) return "/"; string res; for (int i = 0; i < v.size(); ++i) { res += '/' + v[i]; } return res; } };
C++中也有專門處理字符串的機制,我們可以使用stringstream來分隔字符串,然后對每一段分別處理,思路和上面的方法相似,參見代碼如下:
C++ 解法二:
class Solution { public: string simplifyPath(string path) { string res, t; stringstream ss(path); vector<string> v; while (getline(ss, t, '/')) { if (t == "" || t == ".") continue; if (t == ".." && !v.empty()) v.pop_back(); else if (t != "..") v.push_back(t); } for (string s : v) res += "/" + s; return res.empty() ? "/" : res; } };
Java 解法二:
public class Solution { public String simplifyPath(String path) { Stack<String> s = new Stack<>(); String[] p = path.split("/"); for (String t : p) { if (!s.isEmpty() && t.equals("..")) { s.pop(); } else if (!t.equals(".") && !t.equals("") && !t.equals("..")) { s.push(t); } } List<String> list = new ArrayList(s); return "/" + String.join("/", list); } }
參考資料:
https://discuss.leetcode.com/topic/8678/c-10-lines-solution
https://discuss.leetcode.com/topic/7675/java-10-lines-solution-with-stack