• [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; 
        }
        
    };


  • 相关阅读:
    [CF598E] Chocolate Bar
    [CF629D] Babaei and Birthday Cake
    [CF961D] Pair Of Lines
    [CF468B] Two Sets
    [CF767C] Garland
    [CF864E] Fire
    [CF578C] Weakness and Poorness
    [CF555B] Case of Fugitive
    [CF118E] Bertown roads
    [CF1301D] Time to Run
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/2989532.html
Copyright © 2020-2023  润新知