LeetCode 71. Simplify Path
2016-05-08 10:06
288 查看
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
For example,
path =
"/home/", =>
"/home"
path =
"/a/./b/../../c/", =>
"/c"
Code copied from EPI.
#include <sstream> #include <string> #include <vector> #include <iostream> using namespace std; /* I didn't quite understand this problem. This is to simply the given linux-like path command. . stands for current directory. .. stands for going to parent directory. */ string shortestEquivalentPath(const string& path) { if(path.size() == 0) return ""; vector<string> path_names; if(path.front() == '/') path_names.push_back("/"); stringstream ss(path); string token; while(getline(ss, token, '/')) { if(token == "..") { // need to consider the /../../ case. This will be simpiled to .. if(path_names.empty() || path_names.back() == "..") { path_names.push_back(token); } else { path_names.pop_back(); } } else if(token != "." && token != "") { path_names.push_back(token); } } string result; if(!path_names.empty()) { result = path_names.front(); for(int i = 1; i < path_names.size(); ++i) { if(i == 1 && result == "/") { // to in case of starting with "//" result += path_names[i]; } else { result += '/' + path_names[i]; } } } else result = "/"; return result; } int main(void) { cout << shortestEquivalentPath("/home/") << endl; cout << shortestEquivalentPath("/a/./b/../../c/") << endl; cout << shortestEquivalentPath("/../../") << endl; cout << shortestEquivalentPath("//foo/") << endl; }
相关文章推荐
- 【Codevs】1082 线段树练习 3 && 线段树模板
- android studio 出现unsupported modules detected 错误的解决办法
- Hibernate
- Android学习第十周_传感器和LBS
- 产品-商品之布道
- utilities(matlab)—— 多元函数的数值梯度
- pku3013 Big Christmas Tree
- 一切成功源于积累——20160508 美国非农15分钟k线直至收盘 各货币对表现 大幅不及预期 解读分歧
- Hadoop简单入门之伪分布式搭建
- 128. Longest Consecutive Sequence *HARD* -- 寻找无序数组中最长连续序列的长度
- 玩转CSDN博客栏目
- MathType中批量修改公式的格式
- 每CPU变量
- 算法1.1节22
- 移动网站开发中常用的10段JavaScript代码
- winfrom 快捷键
- (2) NSOperation
- 【BZOJ-2055】80人环游世界 上下界费用流 (无源无汇最小费用流)
- XSS攻击处理方案
- iOS三种多线程编程的技术介绍