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

[LeetCode] Simplify Path 简化路径

时间:2015-03-18 15:22:54      阅读:137      评论: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".

 

class Solution {
public:
    string simplifyPath(string path) {
        vector<string> v;
        int i = 0;
        while (i < path.size()) {
            while (path[i] == / && i < path.size()) ++i;
            if (i == path.size()) break;
            int start = i;
            while (path[i] != / && i < path.size()) ++i;
            int end = i - 1;
            string s = path.substr(start, end - start + 1);
            if (s == "..") {
                if (!v.empty()) v.pop_back(); 
            } else if (s != ".") {
                v.push_back(s);
            }
        }
        if (v.empty()) return "/";
        string res;
        for (int i = 0; i < v.size(); ++i) {
            res += / + v[i];
        }
        return res;
    }
};

 

[LeetCode] Simplify Path 简化路径

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4347125.html

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