zoukankan      html  css  js  c++  java
  • Simplify Path

    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;
        }
    };
  • 相关阅读:
    DataContext.ExecuteQuery的两种方法调用
    记一次电脑被清空的感受
    JAVA学习<二>
    JAVA学习记录<一>
    iOS服务器数据请求"汉字编码"问题
    iOS上传图片问题
    iOS类型的转换
    iOS限制输入解决方法
    iOS10权限问题
    JS进阶学习<一>
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3813930.html
Copyright © 2011-2022 走看看