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

【Simplify Path】cpp

时间:2015-05-11 23:32:18      阅读:143      评论: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".

代码:

class Solution {
public:
    string simplifyPath(string path) {
            string result = "";
            path.append("/"); // some input path not end with "/"
            vector<string> ret; // use vector acting as stack
            string tmp_part = "";
            ret.push_back(string(1,path[0]));
            for ( size_t i = 1; i < path.size(); ++i ){
                if ( path[i]==/ ){
                    if ( tmp_part==".." ){
                        if ( ret.size()>1 )
                        {
                            ret.erase(ret.end()-1);
                            ret.erase(ret.end()-1);
                        }
                    }
                    else
                    {
                        if ( tmp_part!="" && tmp_part!="." )
                        {
                            ret.push_back(tmp_part);
                            ret.push_back("/");
                        }
                    }
                    tmp_part = "";
                }
                else
                {
                    tmp_part += path[i];
                }
            }
            if ( ret.size()>1 && ret[ret.size()-1]=="/" ) ret.erase(ret.end()-1);
            for ( size_t i = 0; i < ret.size(); ++i ) result += ret[i];
            return result;
    }
};

tips:

主要思想是stack堆栈的数据结构。

1. 利用"/"来作为间隔判断符号

2. tmp_part为两个"/"之间的字符串部分(需要注意输入的path可能不以"/"结尾,解决办法是人工在path后面补上一个)

3. 如果tmp_part为“..”,则出栈两个元素(前提是栈中元素数目足够)

    如果tmp_part不为“.”, 且不为".",且不为"", 则入栈(注意,还要包括后面的“/”)

其他部分靠题目提供的一些corner cases来debug了。

 

这里用到的一个技巧是vector来代替stack;这样做的好处是返回结果时不用将stack的元素倒序组合。

 

【Simplify Path】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4495746.html

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