现在的位置: 首页 > 综合 > 正文

[leetcode]Simplify Path

2012年11月08日 ⁄ 综合 ⁄ 共 741字 ⁄ 字号 评论关闭

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

 

 

抱歉!评论已关闭.