美文网首页
71. Simplify Path

71. Simplify Path

作者: Al73r | 来源:发表于2017-10-16 16:06 被阅读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) {
            string ans;
            int i=0;
            while(i<path.size()){
                while(i<path.size() && path[i]=='/') i++;
                string tmp;
                while(i<path.size() && path[i]!='/'){
                    tmp += path[i];
                    i++;
                }
                if(tmp=="." || tmp.empty()) continue;
                if(tmp==".."){
                    if(!ans.empty()){
                        int j=ans.size()-1;
                        while(j>=0 && ans[j]!='/') j--;
                        ans.erase(ans.begin()+j, ans.end());
                    }
                }
                else{
                    ans += '/';
                    ans += tmp;
                }
            }
            if(ans.empty()) ans += '/';
            return ans;
        }
    };
    

    思考

    字符串处理特点就是繁杂,大家似乎都很不喜欢这种题,大家的对这种题的评价都不行。

    相关文章

      网友评论

          本文标题:71. Simplify Path

          本文链接:https://www.haomeiwen.com/subject/gankuxtx.html