【Leetcode】【Medium】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"
.
解题:
题意为简化unix路径,即省略多余字符“/”和运算“.”、"..",返回unix的真实路径;
需要考虑的特殊情况是:
1、根目录下操作"..",还是根目录
2、连续两个“/”,可看做无任何作用
3、路径末尾的"/",要消除
思路:
每次取出两个“/”之间的字符,如果是"."或者空字符表示还在本层路径,如果是".."表示返回上一层路径,如果是其他字符,则表示下一层路径名;
用栈来保存每一层路径非常合适,但是后来变成过程中,使用vector来模拟栈操作,在最后整合最终路径时反而更方便。
代码:
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 string res, substr; 5 vector<string> stk; 6 stringstream ss(path); 7 8 while(getline(ss, substr, '/')) { 9 if (substr == ".." and !stk.empty()) 10 stk.pop_back(); 11 else if (substr != ".." && substr != "." && substr != "") 12 stk.push_back('/' + substr); 13 } 14 15 for (int i = 0; i < stk.size(); ++i) 16 res += stk[i]; 17 18 return res.empty() ? "/" : res; 19 } 20 };