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

leetcode 71. Simplify Path

时间:2015-03-03 08:38:50      阅读:183      评论: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".
[Solution]
先用vector把各级合法目录存入:
1) .不用存,..需要pop出上一个目录。
2) ...是合法目录
 1 string simplifyPath(string path) 
 2     {
 3         vector<string> dirs;  
 4         int start = 0, end = 0;
 5         
 6         while (end < path.size())
 7         {
 8             while (start < path.size() && path[start] == /)
 9                 start++;
10             end = start;
11             while (end < path.size() && path[end] != /)
12                 end++;
13             string str = path.substr(start, end - start);
14             if (str == "..")
15             {    
16                 if (!dirs.empty())
17                     dirs.pop_back();
18             }
19             else if (str != "." && str != "")
20             {
21                 dirs.push_back(str);
22             }
23             start = end;
24         }
25         
26         path = "";
27         for (int i = 0; i < dirs.size(); i++)
28             path += "/" + dirs[i];
29         
30         return (path == "") ? "/" : path;
31     }

 

leetcode 71. Simplify Path

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4304513.html

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