[LeetCode] Simplify Path
来源:互联网 发布:音频测试软件 编辑:程序博客网 时间:2024/06/07 14:12
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"
.
[Solution]
class Solution {
public:
// split path by '/'
vector split(string path){
int i = 0;
string str = "";
vector res;
while(i < path.length()){
if(path[i] == '/'){
if(str != ""){
res.push_back(str);
str = "";
}
}
else{
str += path[i];
}
i++;
}
// be careful the last path
if(str != ""){
res.push_back(str);
}
return res;
}
// simplify path
string simplifyPath(string path) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
deque myQueue;
myQueue.push_back("/");
// split path
vector dirs = split(path);
// enqueue
for(int i = 0; i < dirs.size(); ++i){
if(dirs[i] == "."){
continue;
}
else if(dirs[i] == ".."){
if(myQueue.back() == "/" && myQueue.size() == 1){
continue;
}
else{
// pop dir
myQueue.pop_back();
// pop '/'
if(myQueue.size() > 1){
myQueue.pop_back();
}
}
}
else{
if(myQueue.back() != "/"){
myQueue.push_back("/");
}
myQueue.push_back(dirs[i]);
}
}
// dequeue
string res = "";
while(!myQueue.empty()){
res += myQueue.front();
myQueue.pop_front();
}
return res;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
- LeetCode: Simplify Path
- LeetCode Simplify Path
- LeetCode : Simplify Path
- [Leetcode] Simplify Path
- [leetcode] simplify path
- [LeetCode] Simplify Path
- leetcode 100: Simplify Path
- [leetcode]Simplify Path
- [LeetCode]Simplify Path
- [leetCode] Simplify Path
- [leetcode]Simplify Path
- [leetcode] Simplify Path
- [LeetCode] Simplify Path
- leetcode simplify path
- Leetcode: Simplify Path
- LeetCode题解:Simplify Path
- [LeetCode] Simplify Path
- LeetCode Simplify Path
- [LeetCode] Word Search
- [LeetCode] String to Integer(atoi)
- [LeetCode] Sort Colors
- [LeetCode] Sqrt
- 图的存储(前向星)
- [LeetCode] Simplify Path
- 《高性能SQL调优精要与案例解析》一书谈SQL调优(SQL TUNING或SQL优化)学习
- [LeetCode] N-Queens
- [LeetCode] N-Queens II
- [LeetCode] Restore IP Addresses
- RecyclerView和购物车选择模式
- [LeetCode] Maximal Rectangle
- [LeetCode] Palindrome Partitioning
- [LeetCode] Text Justification