Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
- Did you consider the case where path =
"/../"?
In this case, you should return"/". - Another corner case is the path might contain multiple slashes
'/'together, such as"/home//foo/".
In this case, you should ignore redundant slashes and return"/home/foo".
把‘/’当做字符串之间的区分,然后分析字符串便可
.忽略
..回退
其它则全部按符号处理
class Solution {
public:
string simplifyPath(string path) {
string re = "";
stack <string > sk;
int i = 0;
int len = path.length();
while(i<len)
{
if(path[i] == '/')
{
i++;
continue;
}
int j = 0;
while(i+j < len && path[i+j]!= '/')j++;
string temp = path.substr(i,j);
if(temp == "..")
{
if(!sk.empty())
sk.pop();
i = i+2;
}
else if(temp == "."){
i++;
continue;
}
else
{
i = i +j;
sk.push(temp);
}
}
if(sk.empty())return "/";
while(!sk.empty())
{
string temp = sk.top();
re = '/' + temp + re;
sk.pop();
}
return re;
}
};
posted on 2014-03-12 14:23 pengyu2003 阅读(124) 评论(0) 收藏 举报
浙公网安备 33010602011771号