public String simplifyPath(String path) {
Deque<String> stack = new LinkedList<>();
Set<String> skip = new HashSet<>(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;
}
public class Solution {
public String simplifyPath(String path) {
Deque<String> stack = new ArrayDeque<String>();
int end = 0;
int len = path.length();
StringBuilder res = new StringBuilder();
while (end < len) {
StringBuilder sb = new StringBuilder();
sb.append(path.charAt(end++));
while (end < len && path.charAt(end) != '/') {
sb.append(path.charAt(end++));
}
String temp = sb.toString();
if (temp.equals("/..")) {
if (stack.isEmpty()) { // "/.."
continue;
}
stack.pop();
}
else if (temp.equals("/.") || temp.equals("/")) continue; //"/home//foo/"
else {
stack.push(temp);
}
}
for (String item : stack) {
res.insert(0, item);
}
return res.length() == 0 ? "/" : res.toString();
}
}
/*
"/"
"/home/"
"/a/./b/../../c/"
"/.."
"/home//foo/"
*/
public class Solution {
public String simplifyPath(String path) {
int len = path.length();
Stack<String> tokens = new Stack<String>();
String sub_str = "";
for(int i = 0; i < len; i++) {
if(path.charAt(i) == '/') {
if(sub_str != "") {
tokens.push(sub_str);
sub_str = "";
}
} else {
sub_str += path.charAt(i);
}
}
if(sub_str != "") {
tokens.push(sub_str);
sub_str = "";
}
String simp_path = "";
int pop_last = 0;
while(!tokens.empty()) {
String token = tokens.pop();
if(token.equals(".")) continue;
else if(token.equals("..")) {
pop_last++;
continue;
} else if(pop_last > 0) {
pop_last--;
continue;
}
if(simp_path == "") simp_path = token;
else simp_path = token + '/' + simp_path;
}
simp_path = '/' + simp_path;
return simp_path;
}
}