给定一个文档(Unix-style)的完全路径,请进行路径简化。
您在真实的面试中是否遇到过这个题?
Yes
样例
"/home/"
, => "/home"
"/a/./b/../../c/"
, => "/c"
挑战
标签
Expand
-
你是否考虑了 路径 =
"/../"
的情况?在这种情况下,你需返回
"/"
。 -
此外,路径中也可能包含双斜杠
'/'
,如"/home//foo/"
。在这种情况下,可忽略多余的斜杠,返回
"/home/foo"
。
代码:
class Solution {
public:
/**
* @param path the original path
* @return the simplified path
*/
string simplifyPath(string& path) {
// Write your code here
stack<string> st;
string cur = "";
path+="/";
for(int i=0;i<path.length();i++)
{
if(path[i]=='/')
{
if(cur=="..")
{
if(!st.empty())
st.pop();
}
else if(cur=="."){}
else if(cur.length()>0)
{
st.push(cur);
}
cur = "";
}
else
cur+=path[i];
}
string ret = "";
while(!st.empty())
{
ret = "/"+st.top()+ret;
st.pop();
}
if(ret.length()==0)
ret = "/";
return ret;
}
};