leetcode: Simplify Path

来源:互联网 发布:手机和车互联软件 编辑:程序博客网 时间:2024/06/04 19:06

Total Accepted: 7631 Total Submissions: 39051My Submissions


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

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

click to show corner cases.

Corner Cases:


  • Did you consider the case where path = "/../"?In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".In this case, you should ignore redundant slashes and return "/home/foo".


最讨厌字符串处理!!各种边界条件!!

class Solution {public:    string simplifyPath(string path) {        stack< string> stk;        string res = "";        string tmp = "";        for( int i = 0; i < path.size(); ++i){            if( path[i] == '/'){                if( tmp != ""){                    if( tmp == ".."){                        if( !stk.empty())                            stk.pop();                    }                    else if( tmp != "."){                        stk.push(tmp);                    }                    else                        ;                }                tmp = "";            }            else{                tmp += path[i];            }        }        if( tmp != ""){            if( tmp == ".."){                if( !stk.empty())                    stk.pop();            }            else if( tmp != ".")                stk.push(tmp);            else                ;        }        if( stk.empty())            return "/";        while( !stk.empty()){            res = '/' + stk.top() + res;            stk.pop();        }        return res;    }


0 0