[leetcode_71]Simplify Path

将输入路径简化了unix风格的路径。栈即可解决。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
    string simplifyPath(string path) {
        vector<string> paths;
        paths.clear();
        char * split = strtok(const_cast<char*>(path.c_str()), "/");
        while(split != NULL) {
            paths.push_back(split);
            split = strtok(NULL, "/");
        }
        stack<char*> st;
        for(int i = 0; i < paths.size(); i++) {
            if(strcmp(paths[i], ".") == 0) continue;
            if(strcmp(paths[i], "..") == 0) {
                if(!st.empty()) st.pop();
            }
            else {
                st.push(paths[i]);
            }
        }
        paths.clear();
        while(!st.empty()) {
            paths.push_back(st.top());
            st.pop();
        }
        string spath = "";
        for(int i = paths.size() - 1; i >= 0; i--) {
            spath = spath + string("/");
            spath = spath + string(paths[i]);
        }
        if(spath == "")
            spath = spath + string("/");
        return spath;
    }
};
Licensed under CC BY-NC-SA 4.0