Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
package leetCode; import java.util.*; /** * Created by lxw, liwei4939@126.com on 2018/3/10. */ public class L071_Simplify_Path { 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 static void main(String[] args){ L071_Simplify_Path tmp = new L071_Simplify_Path(); String str = "/a/./b/../../c/"; System.out.println(tmp.simplifyPath(str)); } }
本文介绍了一个Java程序,用于简化Unix风格的绝对文件路径。通过解析输入的路径字符串,并使用栈来跟踪目录变化,最终返回规范化的路径。
551

被折叠的 条评论
为什么被折叠?



