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

分析

字符串处理,就是记录每两个“/”之间的字符(跳过连续的“/”)。如果是“.”则不管。如果是正常字母则加入到答案中,并在前面加上“/”。如果是“..”则在答案中删去上一个“/”之后的字符。

实现

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

思考

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given an absolute path for a file (Unix-style), simplify ...
    persistent100阅读 249评论 0 0
  • Given an absolute path for a file (Unix-style), simplify ...
    Jeanz阅读 448评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,869评论 18 139
  • 问题 Given an absolute path for a file (Unix-style), simpli...
    RobotBerry阅读 201评论 0 0
  • 小坚:如果可以预见,你会选择让自己爱的人避开所有的痛苦吗? 小持:不会。一个人内心的承受力随着痛苦的熏染而长养。如...
    阿奋图图阅读 235评论 0 0