Leetcode 71. Simplify Path
2018-02-04 06:44
274 查看
原题:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
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
In this case, you should ignore redundant slashes and return
解决方法:
用deque来保存读到的路径,用stringstream来切分字符串。当读到".."时,deque删除最后一个路径。最后把所有读到的路径拼起来即可。
代码:
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".
解决方法:
用deque来保存读到的路径,用stringstream来切分字符串。当读到".."时,deque删除最后一个路径。最后把所有读到的路径拼起来即可。
代码:
string simplifyPath(string path) { deque<string> d; string res, temp; stringstream s(path); while(getline(s,temp, '/')){ if (temp.empty() || temp ==".") continue; if (temp == ".."){ if (!d.empty()) d.pop_back(); }else{ d.push_back(temp); } } for(auto item: d){ res += "/" + item; } return res.empty() ? "/" : res; }
相关文章推荐
- LeetCode 71. Simplify Path
- leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- Leetcode-71. Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- leetcode 71. Simplify Path
- Leetcode:71. Simplify Path
- leetcode: 71. Simplify Path
- Leetcode 71. Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- leetcode-71. Simplify Path
- [Leetcode] Simplify Path (Java)
- leetcode---Simplify Path---栈
- LeetCode Online Judge 题目C# 练习 - Simplify Path
- LeetCode-71-Simplify Path 无聊模拟
- LeetCode71——Simplify Path
- Simplify Path -- LeetCode