题目:
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 result = ""; path.append("/"); // some input path not end with "/" vector<string> ret; // use vector acting as stack string tmp_part = ""; ret.push_back(string(1,path[0])); for ( size_t i = 1; i < path.size(); ++i ){ if ( path[i]==‘/‘ ){ if ( tmp_part==".." ){ if ( ret.size()>1 ) { ret.erase(ret.end()-1); ret.erase(ret.end()-1); } } else { if ( tmp_part!="" && tmp_part!="." ) { ret.push_back(tmp_part); ret.push_back("/"); } } tmp_part = ""; } else { tmp_part += path[i]; } } if ( ret.size()>1 && ret[ret.size()-1]=="/" ) ret.erase(ret.end()-1); for ( size_t i = 0; i < ret.size(); ++i ) result += ret[i]; return result; } };
tips:
主要思想是stack堆栈的数据结构。
1. 利用"/"来作为间隔判断符号
2. tmp_part为两个"/"之间的字符串部分(需要注意输入的path可能不以"/"结尾,解决办法是人工在path后面补上一个)
3. 如果tmp_part为“..”,则出栈两个元素(前提是栈中元素数目足够)
如果tmp_part不为“.”, 且不为".",且不为"", 则入栈(注意,还要包括后面的“/”)
其他部分靠题目提供的一些corner cases来debug了。
这里用到的一个技巧是vector来代替stack;这样做的好处是返回结果时不用将stack的元素倒序组合。
时间: 2024-11-20 17:03:38