题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
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的路径构成规则:
| 字符 | 含义(英文) | 含义(中文) |
|---|---|---|
| / | root directory | 根目录 |
| / | Directory Separator | 路径分隔符 |
| . | Current Directory | 当前目录 |
| .. | Parent Directory | 上级目录 |
| ~ | Home Directory | 家目录 |
实现技巧:1)可以在path的最后加入一个"/",这样可以统一提取两个“/”之间的字符串,简化程序逻辑;2)采用vector来模拟stack,因为vector除了具备stack的所有功能之外,还有从前到后顺序访问元素的优势,这样可以避免最后对stack中的元素进行反转的额外时间复杂度开销。
代码:
class Solution {
public:
string simplifyPath(string path) {
vector<string> st; // we use vecctor to simulate stack
path += '/'; // for easier programming
for (int i = 1; i < path.size(); i++) {
int pos = path.find('/', i);
string tem = path.substr(i, pos - i);
if (tem == "..") {
if(st.size() > 0) {
st.pop_back();
}
}
else if (tem.size() > 0 && tem != ".") {
st.push_back("/" + tem);
}
i = pos;
}
string ans;
for (auto val: st) {
ans += val;
}
return ans.size() == 0? "/" : ans;
}
};
本文介绍了一个用于简化Unix风格文件路径的算法实现。通过解析输入路径并应用特定规则,如忽略当前目录(.)和返回上级目录(..),该算法能够有效简化路径表达。文章详细解释了路径构成规则,并提供了一段C++代码示例。
1586

被折叠的 条评论
为什么被折叠?



