当前位置: 首页 > 工具软件 > simplify > 使用案例 >

simplify-path

柴英博
2023-12-01

题目:

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> st;
            for(int i=0;i<path.size();i++){
                while(i<path.size()&&path[i]=='/') i++;
                if(i==path.size()) break;
                string tmp;
                while(i<path.size()&&path[i]!='/')
                      tmp+=path[i],i++;
                if(tmp==".") continue;
                else if(tmp=="..") {
                   if(st.size()) st.pop();
                   //对根目录..不做处理。
                }
                else st.push(tmp);
            }
            string ans;
            while(st.size()){
                 ans='/'+st.top()+ans;//栈底放前面
                 st.pop();
            }
            if(ans=="") ans="/";
            return ans;
    }
};
 类似资料: