Leetcode: 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"
.
分析:细节题。在考虑各cornoer cases的基础上完成所需要求即可。在解此题前要有一个大致的执行逻辑,比如如何执行"."和"..",以及将"filename"还是将"filename/"增加到当前结果中。在下面的代码中,如果是"."我们不做操作;如果是"filename"则将"filename/"加到result末尾;如果是“..”,我们先pop出result末尾的'/'(因为我们遇到"filename"是将"filename/"加到result中),然后再将filename从result中pop。这样做逻辑比较清晰,不易出错,刚开始,我的做法是先将"/"加入到result中,然后在分情况处理".",".."以及"filename"的情况,但一直有wrong answer。
class Solution { public: string simplifyPath(string path) { string result; int n = path.length(); //two corner cases if(n == 0) return result; if(path == "/../") return "/"; //push root directory result.push_back('/'); for(int i = 0; i < n;){ while(i < n && path[i] == '/')i++;//skip redundant '/' int j = i; while(j < n && path[j] != '/')j++;//find next '/' if(i == n) break; string file = path.substr(i,j-i);//get file name //three cases if(file == ".."){ if(result != "/"){ result.pop_back();//pop trailing '/' size_t pos = result.find_last_of('/'); result = result.substr(0,pos+1); } }else if(file != "."){ result += file + "/"; } i = j; } if(result.length() > 1 && result.back() == '/') result.pop_back();//pop trailing '/' return result; } };