LeetCode 模拟&栈 Simplify Path
来源:互联网 发布:联合国数据 编辑:程序博客网 时间:2024/04/29 14:50
思想:
模拟栈,只保存路径(目录)名字;
对于“.”,跳过;
对于“..”,若不为空,弹栈;
class Solution {public: string simplifyPath(string path) { vector<string> stack; for(auto i=path.begin(); i!=path.end();) { i++; auto j = find(i, path.end(), '/'); auto s = string(i, j); if(!s.empty() && s != ".") { if(s == "..") { if(!stack.empty()) stack.pop_back(); }else { stack.push_back(s); } } i = j; } stringstream out; if(stack.empty()) { out<<"/"; }else { for(auto s : stack) { out<<"/"<<s; } } return out.str(); }};
学习了stringstream的使用:#include <sstream>
stringstream继承自iostream;
基本用法:
Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str.
eg:
stringstream out;
string s = out.str();
Characters can be inserted and/or extracted from the stream using any operation allowed on both input and outputstreams.
eg:
out<<"Hello,world";
java:
public class Solution { public String simplifyPath(String path) { Deque<String> stack = new LinkedList<String>(); Set<String> skip = new HashSet<String>(Arrays.asList( "..", ".", "" )); for(String dir: path.split("/")) { if(dir.equals("..") && !stack.isEmpty()) { stack.pop(); }else if(!skip.contains(dir)) { stack.push(dir); } } String res = ""; for(String dir: stack) { res = "/" + dir + res; } return res.isEmpty() ? "/" : res; }}
0 0
- LeetCode 模拟&栈 Simplify Path
- leetcode---Simplify Path---栈
- LeetCode-71-Simplify Path 无聊模拟
- LeetCode Simplify Path(栈操作)
- LeetCode 71 Simplify Path (栈)
- 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
- UVA - 10717 - Mint (GCD + LCM)
- libevent源码浅析: 主要的结构体
- 数据结构 - 串的存储表示和实现
- Linux进程间通信——消息队列
- codeblocks 多线程 pthread_create 函数未定义引用 解决办法
- LeetCode 模拟&栈 Simplify Path
- android 定时器封装
- SQL数据库通用数据导出工具(三)
- Capturing 'XX'strongly in this block is likely to lead to a retain cycle
- 使用 Ruby 从 Web 提取信息
- 10.10 5*5矩阵,中间最大,4角4个最小元素
- jQuery获取客户端ip,适用火狐、IE、谷歌、360浏览器
- 如何使用git,初学者教程
- Sql Server服务无法启动,错误代码10048