首页 > 其他 > 详细

Simplify Path

时间:2014-10-29 23:41:29      阅读:313      评论: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".
 
it takes me a lot of time...
 
 1 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4     vector<string> s;
 5     string name;
 6     const char *p = path.c_str();
 7     while (*p != \0)
 8     {
 9         while (*p == /)                   //去除多余的/
10             p++;
11         while (*p != / && *p !=\0)      //分段,用name储存
12         {
13             name.push_back(*p++);
14         }
15         if (name[0] == \0)                //是否是结尾,结尾则不处理
16             ;
17         else if (name.compare("..") == 0)   //判断是否有上一级目录,有则返回上一级目录
18         {
19             if (s.size() > 0)
20                 s.erase(s.end());
21         }
22         else if (name.compare(".") != 0)    //当前目录.不用处理,否则加入到vector中
23         {
24             s.push_back(name);
25         }
26         name.erase(0);
27     }
28     string ret;
29     if (s.size() == 0)                      //特殊情况/
30         return "/";
31     vector<string>::iterator it;
32     for(it=s.begin(); it!=s.end(); it++){
33         ret += "/";
34         ret += *it;
35     }
36     return ret;
37     }
38 };

 

Simplify Path

原文:http://www.cnblogs.com/george-cw/p/4060532.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!