zoukankan      html  css  js  c++  java
  • [leetcode]Simplify Path

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

    For example,
    path = "/home/", => "/home"
    path = "/a/./b/http://www.cnblogs.com/c/", => "/c"

    这个题就是拼体力的,用一个string的stack,然后码就可以了。。。注意边界条件

     

    class Solution {
    public:
        string simplifyPath(string path) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(path.back() != '/') path.push_back('/');
            
            stack<string> s;
            string buffer;
            
            for(int i = 0; i < path.length(); i++){
                if(path[i] == '/'){
                    if(buffer == ".."){
                        if(!s.empty())  s.pop();
                    }else if(buffer != "." && (!buffer.empty())){
                        s.push(buffer);
                    } 
                    
                    buffer.clear();
                    
                }else{
                    buffer.push_back(path[i]);
                }
                
            }
            
            stack<string> tmp;
            while(!s.empty()){
                tmp.push(s.top());
                s.pop();
            }
            
            string ret;
            while(!tmp.empty()){
                ret.push_back('/');
                ret.append(tmp.top());
                tmp.pop();
            }
            
            if(ret.empty()) return "/";
            
            return ret; 
        }
        
    };


  • 相关阅读:
    VBA开发手记
    爬虫之Scrapy框架
    RPA 介绍
    MongoDB入门
    爬虫项目汇总
    coding基本功实践
    wxpy使用
    爬虫-工具篇
    SQLAlchemy使用介绍
    wtforms组件使用实例及源码解析
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/2989532.html
Copyright © 2011-2022 走看看