题目描述
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period .
refers to the current directory. Furthermore, a double period ..
moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /
, and there must be only a single slash /
between two directory names. The last directory name (if it exists) must not end with a trailing /
. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: "/a/./b/../../c/"
Output: "/c"
Example 5:
Input: "/a/../../b/../c//.//"
Output: "/c"
Example 6:
Input: "/a//b////c/d//././/.."
Output: "/a/b/c"
题意:给一个Unix文件路径,返回其最简路径
算法1
题解:我们可以首先获取所有反斜杠之间的内容,那么总共有四种情况.
,..
,file_name
,我们在使用一个栈来维护当前路径。
- 如果读到的是空格或者
.
,那么不做操作 - 如果读到的是文件名,入栈
- 如果读到的是
..
,如果栈不为空就退栈。
最后栈中的元素就是当前文件路径,注意是否为空。
C++ 代码
string simplifyPath(string path) {
int n = path.length();
vector<string> res;
stack<string> st;
for(int i = 0 ;i < n ;)
{
string cur = "";
int j = i + 1;
while(j < n && path[j] != '/')
cur += path[j++];
i = j;
res.push_back(cur);
}
for(int i = 0 ; i < res.size() ;i ++)
{
if(res[i] == "" || res[i] == ".")continue;
else if(res[i] == "..") {if(!st.empty()) st.pop();}
else st.push(res[i]);
}
string ans = "";
while(!st.empty())
{
ans = "/" + st.top() + ans;
st.pop();
}
return ans == "" ? "/":ans;
}
这个答案写的真的很好。我稍微修改了一下。这样应该不需要考虑curr为空的情况了。
class Solution {
public:
string simplifyPath(string path) {
vector[HTML_REMOVED] s;
};
这题用栈确实舒服
这个ans = “/” + st.top() + ans;用的真妙啊
6