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

Simplify Path -- leetcode

时间:2015-04-09 17:39:26      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:leetcode   path   路径   简化   

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".

基本思路:

1. 以字符 /  作为分隔符,取子串。

2. 对 .. 作特殊处理。

3. 即不是. 又不是 ..  则存入栈中

4. 最后串接


所遇到的特殊case,

输入          /...      (连着三个小数点)

期望输出  /..      (亦是连着三个小数点).


进入循环前,在path末尾添加 / , 作为哨兵,可简化代码。


class Solution {
public:
    string simplifyPath(string path) {
        vector<string> stack;
        string name;
        path.push_back('/');
        for (int i=0; i<path.size(); i++) {
            if (path[i] == '/') {
                if (name == "..") {
                     if (!stack.empty()) stack.pop_back();
                }
                else if (name != "." && !name.empty())
                    stack.push_back(name);
                    
                name.clear();
            }
            else
                name.push_back(path[i]);
        }
        
        if (stack.empty()) return "/";
            
        string ans;
        for (auto p: stack)
            ans += "/" + p;
        
        return ans;
    }
};


Simplify Path -- leetcode

标签:leetcode   path   路径   简化   

原文地址:http://blog.csdn.net/elton_xiao/article/details/44960521

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