首页 > 其他 > 详细

[string]Simplify Path

时间:2015-12-11 20:42:45      阅读:273      评论:0      收藏: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".

模拟栈

/*
1.遇到./,当前位置-2,
2.遇到../,当前位置-3,然后回退到上一个斜杠处
测试用例:
.
..
/.
/..
/...
/./
/../
///
/./
/../
/.../
/..../../../../../../
/a../././../
/a.../././..
*/
class Solution {
public:
    string simplifyPath(string path) {
        int i=0,j=0;
        if(path.size()>0){
            path.push_back(/);
        }
        string res(path.size(), );
        while(i<path.size()){
            if(i>0 && path[i]==res[j-1] && path[i]==/) {
                i++;
                continue;
            }
            res[j++] = path[i];
            if(path[i]==/){
                int pre_level_start = i-3>=0? i-3:0;
                if(path.substr(pre_level_start,i-pre_level_start+1)=="/../"){
                    j-=4;
                    while(j-1>=0 && res[j-1]!=/) --j;
                    if(j==0){
                        j=1;
                    }
                }else{
                    pre_level_start = i-2>=0? i-2:0;
                    if(path.substr(pre_level_start,i-pre_level_start+1)=="/./"){
                        j-=2;
                    }
                }
            }
            i++;
        }
        if(j>1 && res[j-1]==/) --j;
        res.erase(res.begin()+j,res.end());
        return res;
    }
};

[string]Simplify Path

原文:http://www.cnblogs.com/zengzy/p/5040096.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!