题目说明
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner
case is the path might contain multiple slashes '/' together,
such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
思路
本题就是对输入的字符串逐个处理的过程,但是要注意两个特殊情况,(1)如果在根目录下输入..,则仍在根目录,而不是跳到上级目录。(2)如果有两个分隔符在一块的话就当做一个分隔符处理。我们只要将输入字符串用”/”分割开来得到一个字符串数组,然后对这个数组内的元素依次处理即可。作者新建了一个Path类,该类包含了一个变量按顺序保存了所有到当前路径的目录名称,提供了一个方法对新输入的字符串进行处理,如果当前路径是根路径,遇到..就不做处理(情况1)。如果新来的字符串是”.”或者空(情况2)也不做处理。其他情况下遇到..删除最顶层目录。遇到普通目录新加一个目录。最后输出结果即可。
代码
import java.util.ArrayList; class Path { private ArrayList<String> paths=new ArrayList<>(); public void ParseNewDir(String dir) { if(dir.equals("")||dir.equals(".")||(dir.equals("..")&&paths.size()==0)) { return; } if(dir.equals("..")) { paths.remove(paths.size()-1); } else { paths.add(dir); } } public String GetFullDir() { if(paths.size()==0) return "/"; StringBuilder sb=new StringBuilder(); for(int i=0;i<paths.size();i++) { sb.append("/"); sb.append(paths.get(i)); } return sb.toString(); } } public class Simplify_Path { public String simplifyPath(String path) { // Note: The Solution object is instantiated only once and is reused by each test case. String[] splits=path.split("/"); Path fullDir=new Path(); for(int i=0;i<splits.length;i++) { String newDir=splits[i]; fullDir.ParseNewDir(newDir); } return fullDir.GetFullDir(); } public static void main(String[] args) { System.out.println(new Simplify_Path().simplifyPath("/../")); } }