码迷,mamicode.com
首页 > 其他好文 > 详细

Simplify Path

时间:2016-09-29 11:20:02      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

Corner Cases:

 

  • 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".
 
Runtime: 6ms
 1 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4         string newPath;
 5         vector<string> directory;
 6         stringstream newString(path);
 7         string temp;
 8         while (getline(newString, temp, /)) {
 9             if (temp == "." || temp == "") continue;
10             else if (temp == ".." && !directory.empty()) directory.pop_back();
11             else if (temp != "..") directory.push_back(temp);
12         }
13         
14         for (string current : directory) {
15             newPath += "/" + current;
16         }
17         return newPath.empty() ? "/" : newPath;
18     }
19 };

 

Simplify Path

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5919169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!