思想:
模拟栈,只保存路径(目录)名字;
对于“.”,跳过;
对于“..”,若不为空,弹栈;
class Solution {
public:
string simplifyPath(string path) {
vector<string> stack;
for(auto i=path.begin(); i!=path.end();) {
i++;
auto j = find(i, path.end(), '/');
auto s = string(i, j);
if(!s.empty() && s != ".") {
if(s == "..") {
if(!stack.empty()) stack.pop_back();
}else {
stack.push_back(s);
}
}
i = j;
}
stringstream out;
if(stack.empty()) {
out<<"/";
}else {
for(auto s : stack) {
out<<"/"<<s;
}
}
return out.str();
}
};
学习了stringstream的使用:#include <sstream>
stringstream继承自iostream;
基本用法:
Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str.
eg:
stringstream out;
string s = out.str();
Characters can be inserted and/or extracted from the stream using any operation allowed on both input and outputstreams.
eg:
out<<"Hello,world";
java:
public class Solution {
public String simplifyPath(String path) {
Deque<String> stack = new LinkedList<String>();
Set<String> skip = new HashSet<String>(Arrays.asList(
"..",
".",
""
));
for(String dir: path.split("/")) {
if(dir.equals("..") && !stack.isEmpty()) {
stack.pop();
}else if(!skip.contains(dir)) {
stack.push(dir);
}
}
String res = "";
for(String dir: stack) {
res = "/" + dir + res;
}
return res.isEmpty() ? "/" : res;
}
}