原题地址:https://leetcode-cn.com/problems/simplify-path/description/
题目描述:
给定一个文档 (Unix-style) 的完全路径,请进行路径简化。
例如,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
边界情况:
- 你是否考虑了 路径 =
"/../"
的情况?
在这种情况下,你需返回"/"
。 - 此外,路径中也可能包含多个斜杠
'/'
,如"/home//foo/"
。
在这种情况下,你可忽略多余的斜杠,返回"/home/foo"
。
解题方案:
利用栈来辅助解题,通过stringstream完成字符串的拆分,这里利用到了函数getline()。
注意:学习关键字auto的用法和stringstream的用法
。
class Solution {
public:
string simplifyPath(string path) {
vector<string> st;
vector<string> nodes;
string result;
split(path, '/', nodes);
for(auto node : nodes) {
if(node == "" || node == ".") continue;
if(node == ".." && !st.empty()) st.pop_back();
else if(node != "..") st.push_back(node);
}
for(auto it : st) result += "/" + it;
return result.empty() ? "/" : result;
}
void split(string s, char delim, vector<string>& nodes) {
string temp;
stringstream ss(s);
while(getline(ss, temp, delim)) {
nodes.push_back(temp);
}
}
};