[LeetCode] Simplify Path

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;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注