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

    }

    

};


 

 

你可能感兴趣的:(LeetCode)