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

Simplify Path

时间:2014-06-04 19:32:14      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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".
bubuko.com,布布扣
class Solution {
private:
    int index;
    string path;
    string getpath()
    {
        index++;
        string newpath="";
        while(index<path.length() && path[index]!=/)
        {
            newpath=newpath+path[index];
            index++;            
        }
        return newpath;
    }
public:
    string simplifyPath(string path) 
    {
        this->path=path;
        stack<string> stk;
        index=0;
        while(index<path.size())
        {
            string newpath=getpath();
            if(newpath=="..")
            {
                if(stk.empty()==false)
                    stk.pop();
                continue;
            }
            if(newpath=="." || newpath==""continue;
            stk.push(newpath);
        }
        string result="";
        while(stk.empty()==false)
        {
            result=/+stk.top()+result;
            stk.pop();
        }
        if(result.length()==0) result="/";
        return result;
    }
};
bubuko.com,布布扣

Simplify Path,布布扣,bubuko.com

Simplify Path

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759476.html

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