LeetCode71.简化路径

时间:2023-03-08 17:35:19

给定一个文档 (Unix-style) 的完全路径,请进行路径简化。

例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

边界情况:

    • 你是否考虑了 路径 = "/../" 的情况?
      在这种情况下,你需返回 "/" 。
    • 此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。
      在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。
package 题库;

import java.util.Stack;

public class SimplifyPath71 {

    public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>(); String[] paths = path.split("/+"); for (String s:paths) {
if (s.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!s.equals(".") && !s.equals("")) {
stack.push(s);
}
}
String res = "";
while (!stack.isEmpty()) {
res = "/"+stack.pop() + res;
}
if (res.length() == 0) {
return "/";
}
return res; } }