LEETCODE: Simplify Path

来源:互联网 发布:股票赢家软件 编辑:程序博客网 时间:2024/06/05 21:34

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

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


汗!不熟悉linux啊,'.'是当前目录,‘..’是到上一级目录。其他的都没有特殊含义。


class Solution {public:    string simplifyPath(string path) {        stack<string> words;        path += '/';        string current;        for(int ii = 0; ii < path.length(); ii ++) {            if(path[ii] != '/') {                current += path[ii];            }            else {                if(current.length() == 1 && current[0] == '.') {                    current.clear();                    continue;                }                                if(current.length() == 2 && current[0] == '.' && current[1] == '.') {                    if(!words.empty()) {                        words.pop();                    }                    current.clear();                    continue;                }                                if(!current.empty()) {                    words.push(current);                    current.clear();                    continue;                }            }        }                string result;        while(!words.empty()) {            result = '/' + result;            result = words.top() + result;            words.pop();        }                if(!result.empty()) {            result = result.substr(0, result.length() - 1);        }                result = "/" + result;                return result;    }};




0 0
原创粉丝点击