题目描述
简化Unix风格的路径,需要考虑的包括"/../","//","/./"等情况
输入描述
Unix风格的路径
输出描述
简化后的Unix风格路径
示例输入
/a/./b/../../c/
示例输出
/c
思路
用一个栈来存储路径中的目录信息,遍历读入的string字符串,当遇到‘/’时跳过,遇到不为‘/’的字符时累加从而得到当前目录信息,若目录为‘.’,则continue,若目录为‘..’且栈不为空则pop,否则push该目录到栈中。
循环结束后,栈中的目录则为简化后的目录,但排序为逆序,则通过再次循环累加到string变量中(注意加‘/’),输出该变量。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(){
string str;
cin >> str;
int len = str.length();
stack<string> stringStack;
int i = 0;
string tmp;
while (i < len)
{
while (i < len && str[i] == '/')
i++;
tmp.clear();
while (i < len && str[i] != '/')
{
tmp += str[i];
i++;
}
if (tmp == "..")
{
if (!stringStack.empty())
stringStack.pop();
}
else if (tmp == ".")
continue;
else if (!tmp.empty())
{
stringStack.push(tmp);
}
}
if (stringStack.empty()){
cout << "/";
return 0;
}
string result = "";
while (!stringStack.empty())
{
result = "/" + stringStack.top() + result;
stringStack.pop();
}
cout << result;
return 0;
}