这题比较elegant的解法是弄个状态机什么的吧 遇到什么字符进什么状态触发什么操作之类的... 懒得弄那么复杂了直接if...else了...
-
class Solution {
-
public:
-
string simplifyPath(string path) {
-
string re;
-
if(path.empty()) return re;
-
re.push_back('/');
-
for(int i=0;i<path.length();)
-
{
-
if(i<(int)path.length()-3)
-
{
-
if(0==strcmp(path.substr(i,3).c_str(),"/./"))
-
{if(re[re.length()-1]!='/')re.push_back('/');i+=2;continue;}
-
if(0==strcmp(path.substr(i,4).c_str(),"/../"))
-
{if(re.length()>1)do{re.pop_back();}while(re[re.length()-1]!='/');i+=3;continue;}
-
}
-
else if(i==path.length()-3)
-
{
-
if(0==strcmp(path.substr(i,3).c_str(),"/./")) break;
-
if(0==strcmp(path.substr(i,3).c_str(),"/..")) {if(re.length()>1)do{re.pop_back();}while(re[re.length()-1]!='/');break;}
-
}
-
else if(i==path.length()-2)
-
{
-
if(0==strcmp(path.substr(i,2).c_str(),"//")||0==strcmp(path.substr(i,2).c_str(),"/.")) break;
-
}
-
else if(i==path.length()-1)
-
{
-
if('/'==path[i]) break;
-
}
-
-
if(re[re.length()-1]!='/'||path[i]!='/')re.push_back(path[i]);
-
i++;
-
}
-
if(re.length()>1&&'/'==re[re.length()-1]) re.pop_back();
-
return re;
-
}
-
};
阅读(444) | 评论(0) | 转发(0) |