[LintCode] Simplify Path 简化路径
2016-07-28 23:54
417 查看
Given an absolute path for a file (Unix-style), simplify it.
Have you met this question in a real interview?
Example
Challenge
Did you consider the case where path =
In this case, you should return
Another corner case is the path might contain multiple slashes
In this case, you should ignore redundant slashes and return
LeetCode上的原题,请参见我之前的博客Simplify Path。
解法一:
解法二:
Have you met this question in a real interview?
Example
"/home/", =>
"/home"
"/a/./b/../../c/", =>
"/c"
Challenge
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".
LeetCode上的原题,请参见我之前的博客Simplify Path。
解法一:
class Solution { public: /** * @param path the original path * @return the simplified path */ string simplifyPath(string& path) { int left = 0, right = 0, n = path.size(); stack<string> s; string res = ""; while (right < n) { while (left < n && path[left] == '/') ++left; right = left; while (right < n && path[right] != '/') ++right; string t = path.substr(left, right - left); if (t == "..") { if (!s.empty()) s.pop(); } else if (t != ".") { if (!t.empty()) s.push(t); } left = right; } while (!s.empty()) { res = "/" + s.top() + res; s.pop(); } return res.empty() ? "/" : res; } };
解法二:
class Solution { public: /** * @param path the original path * @return the simplified path */ string simplifyPath(string& path) { string res, t; stringstream ss(path); vector<string> v; while (getline(ss, t, '/')) { if (t == "" || t == ".") continue; if (t == ".." && !v.empty()) v.pop_back(); else if (t != "..") v.push_back(t); } for (string s : v) res += "/" + s; return res.empty() ? "/" : res; } };
相关文章推荐
- ACM算法模板
- 多线程知识点简单总结
- Scala入门No.1
- 机器学习-入门介绍
- CVE-2012-0003 Microsoft Windows Media Player ‘winmm.dll’ MIDI文件解析远程代码执行漏洞 分析
- 关于java线程池和相关
- IDL出现% Program caused arithmetic error: Floating illegal operand 错误!!
- 进阶项目5-个税计算器之码数分离
- Closure表 冗余 小结
- for语句
- yum源配置EPEL
- android ExpandableTextView-自定义可以动态展开/收缩显示长文本的TextView
- Android的四大组件之-Activity的启动模式
- ruby中文编码
- 双缓冲绘图
- eclipse最常用快捷键整理
- 调用构造函数
- [Unity热更新]tolua# & LuaFramework(十一):实践
- 使用 IOS7 原生API进行二维码条形码的扫描
- Android Proguard工具使用和配置详解