LeetCode 71
Simplify Path
Problem Description:
简化输入的绝对路径
具体的题目信息:
https://leetcode.com/problems/simplify-path/description/Attention:
(1)/home/..abvh简化后仍是/home/..abvh
(2)/home/…简化后仍是/home/…
也就是说除了../会返回上一目录,其他的情况照常输出
(3)如果最终化简后结果为空,输出“/”Solution:
用两个变量i和j分别记录两个/的位置,读取相邻两个/之间的字符串并用栈来存储。如果相邻两个/之间的字符串是“.”或者是“”,则不做处理。
如果相邻两个/之间的字符串是“..”则弹出栈顶元素。
其他情况将相邻两个/之间的字符串压入栈中。
class Solution {
public:
string simplifyPath(string path) {
stack<string> p;
string temp = "";
for (int i = 0; i < path.length(); ) {
if (path[i] == '/') {
int j = i+1;
while(j<path.length() && path[j] != '/') {
temp += path[j];
j++;
}
if (temp == "."||temp == "") {
} else if (temp == "..") {
if (!p.empty()) {
p.pop();
}
} else {
p.push(temp);
}
temp = "";
i = j;
}
}
string result = "";
vector<string> re;
while(!p.empty()) {
re.push_back(p.top());
p.pop();
}
if (re.size() == 0) {
result += '/';
} else {
for (int i = re.size()-1; i >= 0; i--) {
result += '/';
result += re[i];
}
}
return result;
}
};