LeetCode | Simplify Path
2013-12-23 12:15
411 查看
题目:
Given an absolute path for a file (Unix-style), simplify it.For example,
path =
"/home/", =>
"/home"
path =
"/a/./b/../../c/", =>
"/c"
click to show corner cases.
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".
思路:
利用堆栈来存储目录并完成消除。
代码:
class Solution { public: stack<string> mystack; string simplifyPath(string path) { for(int i=0;i<path.size();i++) { //获得下一字符串 string cur; if(path[i]=='/') { cur="/"; } else { while(i<path.size()&&path[i]!='/') { cur.push_back(path[i++]); } if(i<path.size()) { i--; } } //获得下一字符串 if(mystack.size()==0) { mystack.push(cur); } else { if(mystack.top()=="/"&&cur=="/") { continue; }//忽略相邻的“//” else if(cur==".") { continue; }//忽略“.” else if(cur==".."&&mystack.top()=="/") { mystack.pop(); while(mystack.size()>0&&mystack.top()!="/") { mystack.pop(); } }//返回上一层目录 else { mystack.push(cur); } } } string str; if(mystack.size()>1&&mystack.top()=="/") { mystack.pop(); }//去掉最后一个“/” stack<string> reverse; while(mystack.size()>0) { reverse.push(mystack.top()); mystack.pop(); }//反转堆栈 while(reverse.size()>0) { str+=reverse.top(); reverse.pop(); }//生成字符串 if(str.size()==0) str="/"; return str; } };
另一种实现:
class Solution { public: string simplifyPath(string path) { if(path.size() == 0){ return ""; } list<string> q; string cur; for(int i = 0; i < path.size() + 1; i++){ if(i == path.size() || path[i] == '/'){ if(cur.size() > 0){ if(cur == ".." && q.size() > 0 && q.back() != ".."){ q.pop_back(); } else if(cur == ".." && q.size() == 0){ } else if(cur != "."){ q.push_back(cur); } cur.clear(); } } else{ cur.push_back(path[i]); } } string result; for (std::list<string>::iterator it=q.begin(); it != q.end(); ++it){ result.push_back('/'); for(int j = 0; j < (*it).size(); j++){ result.push_back((*it)[j]); } } if(result == ""){ return "/"; } return result; } };
相关文章推荐
- 145_leetcode_Simplify Path
- 【leetcode刷题笔记】Simplify Path
- Leetcode135: Simplify Path
- LeetCode 71 Simplify Path
- [LeetCode] Simplify Path 简化路径
- LeetCode -- Simplify Path
- [leetcode] Simplify Path
- LeetCode 071 Simplify Path
- Leetcode71- Simplify Path
- LeetCode - Simplify Path
- LeetCode-71-Simplify Path 无聊模拟
- 【leetcode】【71】Simplify Path
- leetcode 71. Simplify Path
- leetcode 71. Simplify Path
- 【LeetCode】Simplify Path 解题报告
- [Leetcode]Simplify Path
- LeetCode(45) Simplify Path
- LeetCode : Simplify Path
- LeetCode | Simplify Path
- Leetcode-71. Simplify Path