简化路径
解法一:利用栈
import java.util.Stack;
public class LeetCode_071 {
public static String simplifyPath(String path) {
Stack<String> paths = new Stack<>();
String str = "";
for (char c : path.toCharArray()) {
if (c == '/') {
if (str.length() != 0) {
if (str.equals(".")) {
} else if (str.equals("..")) {
if (!paths.isEmpty()) {
paths.pop();
}
} else {
paths.push(str);
}
str = "";
}
} else {
str += c;
}
}
if(str.length() != 0) {
if (str.equals(".")) {
} else if (str.equals("..")) {
if (!paths.isEmpty()) {
paths.pop();
}
} else {
paths.push(str);
}
}
if (paths.isEmpty()) {
return "/";
}
Stack<String> reversePaths = new Stack<>();
while (!paths.isEmpty()) {
reversePaths.push(paths.pop());
}
String result = "";
while (!reversePaths.isEmpty()) {
result += "/" + reversePaths.pop();
}
return result;
}
public static void main(String[] args) {
System.out.println(simplifyPath("/a//b////c/d//././/.."));
}
}