71. Simplify Path
来源:互联网 发布:手机变脸软件 编辑:程序博客网 时间:2024/06/06 05:03
开始没有理解题意,后来看别人的理解,这道题要用到栈。
这道题的要求是简化一个Unix风格下的文件的绝对路径。
字符串处理,由于”..”是返回上级目录(如果是根目录则不处理),因此可以考虑用栈记录路径名,以便于处理。需要注意几个细节:
重复连续出现的’/’,只按1个处理,即跳过重复连续出现的’/’;
如果路径名是”.”,则不处理;
如果路径名是”..”,则需要弹栈,如果栈为空,则不做处理;
如果路径名为其他字符串,入栈。
最后,再逐个取出栈中元素(即已保存的路径名),并在前面用’/’分隔并连接起来,不过要注意顺序呦。
#include<iostream>#include<string>#include<stack>using namespace std;class Solution {public: string simplifyPath(string path) { stack<string>temp; int i=0; while(i<path.size()) { while(i<path.size()&&path[i]=='/') i++; string s; while(i<path.size()&&path[i]!='/') s=s+path[i++]; if(".."==s&&!temp.empty()) temp.pop(); else if(".."!=s&&"."!=s&&s!="") temp.push(s); } if(temp.empty()) return "/"; string ret; while(!temp.empty()) { ret='/'+temp.top()+ret; temp.pop(); } return ret; }};int main(){ string path; cin>>path; Solution solve; cout<<solve.simplifyPath(path)<<endl; return 0;}
0 0
- LeetCode 71. Simplify Path
- LeetCode --- 71. Simplify Path
- [Leetcode] 71. Simplify Path
- [leetcode] 71.Simplify Path
- 71.Simplify Path
- 71.Simplify Path
- 71. Simplify Path
- [leetcode] 71.Simplify Path
- 71. Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- 71. Simplify Path LeetCode
- 71. Simplify Path
- 71. Simplify Path
- 71. Simplify Path
- 71. Simplify Path
- leetcode 71. Simplify Path
- leetcode交换相邻的两个节点的值
- 用Python做投资-关于term spread
- 内存初始化(上)
- Laxcus大数据管理系统单机集群版
- Android中的调色板功能的实现
- 71. Simplify Path
- emacs注释快捷键
- 四种C#实现播放声音的方法,如DirectX ,SoundPlayer, Windows Media Player
- pandas处理excel数据经验
- 从零开始学_JavaScript_系列(31)——事件代理/事件委托
- 哈夫曼树的实现
- MySQL 字符集与校对规则
- HDU 1269 迷宫城堡 (Tarjan 算法)
- 从此起飞~博客