zoukankan      html  css  js  c++  java
  • 71. Simplify Path (Stack)

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

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

    注意:题目中已限定是absolute path - contains the root directory and all other subdirectories in which a file or folder is contained.

    class Solution {
    public:
        string simplifyPath(string path) {
            stack<string> pathStack;
            string splitPath = path;
            string curPath;
            string ret="";
            int pos = 0;//absolute path, so path[0]=='/'
            while(pos!=string::npos && pos+1 < splitPath.length()){
                splitPath = splitPath.substr(pos+1); 
                pos = splitPath.find_first_of('/');
                if(pos!=0){ //ignore second '/'
                    curPath = splitPath.substr(0,pos);
                    
                    if(curPath=="."){//ignore './'
                        
                    }
                    else if(curPath==".." ){ //ignore '/..'
                        if(!pathStack.empty()) pathStack.pop();
                    }
                    else{ //除了"."以及".."以外的都是文件名,比如"..."
                        pathStack.push(curPath);
                    }
                }
            }
            
            if(pathStack.empty()) return "/";
            while(!pathStack.empty()){
                ret = "/" + pathStack.top() + ret;
                pathStack.pop();
            }
            return ret;
        }
    };
  • 相关阅读:
    MSBuild、条件编译、预处理命令
    批量数据插入SqlBulkCopy
    WPF 双向绑定
    编程思想之一
    python 提交表单
    python 添加用户
    python 分页
    day9 IO多路复用
    day9 线程、进程和协程深入版
    day8 进程、线程 简介版
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854127.html
Copyright © 2011-2022 走看看