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

Simplify Path

时间:2014-06-30 12:05:08      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   get   strong   

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".
思路:利用栈来对字符串进行处理。str是保存"/"和"/"间的的字符串。有以下一些情形:
1)当path[i]=="/"时,然后对str进行处理a)str==".."时看栈是否为空,去除栈顶元素(b)str!="."&&str!="",则入栈(c)其他情况,str="";
2)当path[i]!="/"时,path[i]加入到str中去。
注意:有可能最后一个字符串不是以"/"结束,所以这一部分还得按照1)步骤来处理。
class Solution {
public:
    string simplifyPath(string path) {
        stack<string> s;
        string str;
        int n=path.size();
        for(int i=0;i<n;i++)
        {
            if(path[i]==/)
            {
                if(str=="..")
                {
                    if(!s.empty())
                        s.pop();
                }
                else if(str!="."&&str!="")
                    s.push(str);
                str="";
            }
            else
            {
                str+=path[i];
            }
        }
        /*处理最后字符不是以"/"结束,但是str保存了一部分字符串*/
        if(str=="..")
        {
            if(!s.empty())
                s.pop();
        }
        else if(str!="."&&str!="")
            s.push(str);
        if(s.empty())
            return "/";
        string result;
        while(!s.empty())
        {
            result="/"+s.top()+result;
            s.pop();
        }
        return result;
    }
};

 

Simplify Path,布布扣,bubuko.com

Simplify Path

标签:style   blog   http   color   get   strong   

原文地址:http://www.cnblogs.com/awy-blog/p/3813930.html

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