71. Simplify Path

2017-10-16  本文已影响0人  Al73r

题目

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

思考

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

上一篇下一篇

猜你喜欢

热点阅读