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

Leetcode: Simplify Path

时间:2014-12-02 19:04:40      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   sp   for   on   

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

分析:细节题。在考虑各cornoer cases的基础上完成所需要求即可。在解此题前要有一个大致的执行逻辑,比如如何执行"."和"..",以及将"filename"还是将"filename/"增加到当前结果中。在下面的代码中,如果是"."我们不做操作;如果是"filename"则将"filename/"加到result末尾;如果是“..”,我们先pop出result末尾的‘/‘(因为我们遇到"filename"是将"filename/"加到result中),然后再将filename从result中pop。这样做逻辑比较清晰,不易出错,刚开始,我的做法是先将"/"加入到result中,然后在分情况处理".",".."以及"filename"的情况,但一直有wrong answer。

class Solution {
public:
    string simplifyPath(string path) {
        string result;
        int n = path.length();
        //two corner cases
        if(n == 0) return result;
        if(path == "/../") return "/";
        //push root directory
        result.push_back(/);
        for(int i = 0; i < n;){
            while(i < n && path[i] == /)i++;//skip redundant ‘/‘
            int j = i;
            while(j < n && path[j] != /)j++;//find next ‘/‘
            
            if(i == n) break;
            
            string file = path.substr(i,j-i);//get file name
            //three cases
            if(file == ".."){
                if(result != "/"){
                    result.pop_back();//pop trailing ‘/‘
                    size_t pos = result.find_last_of(/);
                    result = result.substr(0,pos+1);
                } 
            }else if(file != "."){
                result += file + "/";
            }
            i = j;
        }
        if(result.length() > 1 && result.back() == /) result.pop_back();//pop trailing ‘/‘
        return result;
    }
};

 

Leetcode: Simplify Path

标签:style   blog   http   io   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4138019.html

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