您的位置:首页 > 其它

CCF 201604-3 路径解析

2017-09-16 13:31 246 查看
一开始没有考虑名字内有可能出现"."和"..",直接使用solve版本,即一个字符一个字符处理,得到80分,后来的solve2的做法是每次以"/"为分隔符,直到下一个“/”为止,即使用了两层循环,解决了如何分辨"."和".."是否在名字出现的问题。
对于当前路径的解析本来只需要一次即可,但懒得去拷贝stack,所以每次都调用solve2重新生成一个当前路径的栈。
还要注意路径有可能是空串,而cin会忽略空白字符,应该使用getline,由于getline不忽略回车符,使用前要看一下上一步输入中有无残留的回车符,有的话要用getchar()处理掉。


#include<iostream>
#include<string>
#include<stack>
#define REL 1;

using namespace std;

void solve(string &c_str, stack<string>& c_dir)
{
string part;
part = "";
for(int i = 0; i < c_str.length(); i++)
{
if(c_str[i]=='/')
{
if(part.length())
{
c_dir.push(part);   part = "";
}
}else if(c_str[i]=='.')
{
if(c_str[i+1]=='.')
{
i += 2;
c_dir.push("..");
}

}else
{
part += c_str[i];
}
}
if(part.length())
{
c_dir.push(part);   part = "";
}
}
void solve2(string &c_str, stack<string>& c_dir)
{
string part;
part = "";
for(int i = 0; i < c_str.length();i++)
{

if(c_str[i] != '/')
{
int start = i;
while(i<c_str.length() && c_str[i] != '/') i++;
int len = i-start;
part = c_str.substr(start, len);
if(part!=".")
c_dir.push(part);
}
}
}
int main()
{
int t;
cin >> t;
getchar();

string c_str;
getline(cin, c_str);
/*  stack<string> c_dir;
solve2(c_str, c_dir);
stack<string> anti_c_dir;
while(!c_dir.empty())
{
anti_c_dir.push(c_dir.top());
c_dir.pop();
}
*/

while(t--)
{
string str;
getline(cin, str);
stack<string> dir;
solve2(str, dir);
if(!str.length() || str[0]!='/')
{

stack<string> c_dir;
solve2(c_str, c_dir);
stack<string> anti_c_dir;
while(!c_dir.empty())
{
anti_c_dir.push(c_dir.top());
c_dir.pop();
}

stack<string> anti_dir;
while(!dir.empty())
{
anti_dir.push(dir.top());   dir.pop();
}
while(!anti_c_dir.empty())
{
dir.push(anti_c_dir.top()); anti_c_dir.pop();
}
while(!anti_dir.empty())
{
dir.push(anti_dir.top());   anti_dir.pop();
}
}//if

stack<string> anti_dir;
while(!dir.empty())
{
anti_dir.push(dir.top());
dir.pop();
}

stack<string> reg_dir;
while(!anti_dir.empty())
{
string part = anti_dir.top();
anti_dir.pop();
if(part!="..")
{
reg_dir.push(part);
}
else
{
if(!reg_dir.empty())
reg_dir.pop();
}
}

stack<string> reg_anti_dir;
while(!reg_dir.empty())
{
reg_anti_dir.push(reg_dir.top());
reg_dir.pop();
}

if(reg_anti_dir.empty())
cout << "/\n";
else
{
while(!reg_anti_dir.empty())
{
cout << "/" << reg_anti_dir.top();
reg_anti_dir.pop();
}
cout << endl;
}
}//while(t--)

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息