首页 > 其他 > 详细

Simplify Path

时间:2016-09-29 11:19:45      阅读:132      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!