题意:给你一个linux路径,让你求出他的最终路径。
题解:用栈模拟。
class Solution {
public:
string simplifyPath(string path) {
stack<string> sta;
int n = path.length();
for(int i = 0; i < n;)
{
while(i < n && path[i] == '/') i++;
string s = "";
while(i < n && path[i] != '/') s += path[i++];
if(s == ".." && !sta.empty()) sta.pop();
else if(s != "" && s != "." && s != "..")
sta.push(s);
}
string ans = "";
if(sta.empty()) return "/";
while(!sta.empty())
{
ans = "/" + sta.top() + ans;
sta.pop();
}
return ans;
}
};