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

leetcode No71. Simplify Path

时间:2016-08-03 18:47:11      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

Question:

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

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

Algorithm:

根据(Unix-style)路径规则,把字符串一"/"分割,遍历字符串,/????/????用临时字符串储存,如果s不是“..”或者“”或者“.”则入栈。
这样,字符串就分割完了,再一次出栈。

Accepted Code:

class Solution {
public:
    string simplifyPath(string path) {
        int N=path.size();
        stack<string> s;
        for(int i=0;i<N;)
        {
            while(i<N&&path[i]=='/')   //遇到/跳过
                i++;
            string temp="";           //记录字符串
            while(i<N&&path[i]!='/')
            {
                temp.push_back(path[i]);
                i++;
            }
            if(temp==".."&&s.empty()==0)
                s.pop();
            else if(temp!=""&&temp!=".."&&temp!=".")
                s.push(temp);
        }
        if(s.empty())   
            return "/";
        string res=""; 
        while(!s.empty())
        {
            res="/"+s.top()+res;
            s.pop();
        }
        return res;
    }
};


leetcode No71. Simplify Path

标签:

原文地址:http://blog.csdn.net/u011391629/article/details/52105367

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