class Solution {
public:
string simplifyPath(string path) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(path.empty()) return "";
if(path[path.size()-1] != '/') path += "/";
int N = path.size();
stack<string> s;
string tmp;
for(int i = 0; i < N; i++){
if(path[i] == '/'){
if(tmp == ".."){
if(!s.empty()) s.pop();
}else if(!tmp.empty() && tmp != "." && tmp != ".."){
s.push(tmp);
}
tmp.clear();
}else{
tmp += path[i];
}
}
//reverse stack
stack<string> s1;
while(!s.empty()){
s1.push(s.top());
s.pop();
}
string result = "";
while(!s1.empty()){
result += "/";
result += s1.top();
s1.pop();
}
return result == "" ? "/" : result;
}
};
[leetcode]Simplify Path
最新推荐文章于 2019-11-02 16:49:34 发布