LeetCode---Simplify Path
2015-11-14 17:15
387 查看
题目大意:给出一个UNIX-style的路径,将其进行简化,如果遇见“/.”则保持当前路径 ,如果遇见“/..”则返回上一层路径,最后输出简化后的路径。
算法思想:
1.将给出的路径进行分割将每一层路径存储在容器中。
2.按照简化规则进行路径简化,遍历容器如果遇见“.”则continue,如果遇见“..”则进行出栈操作(栈不空),如果是其他字符串则入栈。
3.将栈中存储的简化后的路径单元拼接起来。
4.返回简化后的路径。
代码如下:
算法思想:
1.将给出的路径进行分割将每一层路径存储在容器中。
2.按照简化规则进行路径简化,遍历容器如果遇见“.”则continue,如果遇见“..”则进行出栈操作(栈不空),如果是其他字符串则入栈。
3.将栈中存储的简化后的路径单元拼接起来。
4.返回简化后的路径。
代码如下:
class Solution { public: string simplifyPath(string path) { if(path.size()<=1) return "/"; vector<string> str; stack<string> str_pat; string temp="",res=""; for(char c:path){ if(c!='/') temp+=c; else{ if(temp.size()!=0){ str.push_back(temp); temp=""; } } } if(temp.size()!=0) str.push_back(temp); for(string s:str){ if(s=="."){ continue; } else if(s==".."){ if(!str_pat.empty()) str_pat.pop(); } else{ str_pat.push(s); } } while(!str_pat.empty()){ temp="/"+str_pat.top()+res; str_pat.pop(); res=temp; temp=""; } if(res.size()==0) res="/"; return res; } };
相关文章推荐
- 九度OJ 1261:寻找峰值点 (基础题)
- 九度OJ 1261:寻找峰值点 (基础题)
- 1936 哪一瓶是毒药?
- 功能测试内容
- Testing Round #12
- 深入学习微框架:Spring Boot
- c++中string类的详解
- 浅谈Thread和Runnable
- ubuntu sublime中文输入
- Spark修炼之道(基础篇)——Linux大数据开发基础:第十三节:Shell编程入门(五)
- java文件IO操
- Struts2 学习系列 (6) 消息处理与国际化
- layout_width与layout_weight
- C++之string学习笔记(1)
- Android系统手机端抓包方法
- UI第四天 触摸 响应者链 target-action
- 隐式数据共享 深拷贝 浅拷贝
- javascript正则表达式
- HDU 2151 Worm(和树塔问题差不多)
- android内核编译及模拟器运行过程记录