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

[LeetCode] Simplify Path

时间:2015-07-28 16:04:11      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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

解题思路:

化简路径。可以用一个栈来记录。遍历原路径,遇到/,则判断最近一个单词。若为"."则什么也不做。若"..",弹出栈顶元素,否则入栈。

有一个比较巧的办法是,直接在path后面添加一个斜杠,这样就能避免讨论后面有斜杠还是没有斜杠了。

class Solution {
public:
    string simplifyPath(string path) {
        stack<string> ss;
        path = path + "/";
        int len = path.length();
        string s="";
        for(int i=0; i<len; i++){
            if(path[i]=='/'){
                if(s==".."){
                    if(!ss.empty()){
                        ss.pop();
                    }
                }else if(s!=""&&s!="."){
                    ss.push(s);
                }
                s="";
            }else{
                s=s+path[i];
            }
        }
        while(!ss.empty()){
            s = string("/") + ss.top() + s;
            ss.pop();
        }
        if(s==""){
            s="/";
        }
        return s;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Simplify Path

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47105813

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