Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
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"
.
所以把字符按照"/" 分出来 如果是"." 或者空(// 分出来是空)不做任何操作"当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。当遇到"/./"则表示是本级目录,无需做任何特殊操作。当遇到"//"则表示是本级目录,无需做任何操作。当遇到其他字符则表示是文件夹名,无需简化。当字符串是空或者遇到”/../”,则需要返回一个"/"。当遇见"/a//b",则需要简化为"/a/b"。"
如果是".." 就把arraylist中前一个数删除
如果是其他的就写入arraylist
当最后所有都写入arraylist完之后把arraylist中的string放入一个string中并以"/"相隔
如果最后的string长度为0, 就返回"/"
public class Solution { public String simplifyPath(String path) { if (path == null || path.length() == 0) { return path; } String[] list = path.split("/"); ArrayList<String> tem = new ArrayList<String>(); for (int i = 0; i < list.length; i++) { if (list[i].equals(".") || list[i].length() == 0) { continue; } else if (list[i].equals("..")) { if (tem.size() > 0) { tem.remove(tem.size() - 1); } } else { tem.add(list[i]); } } StringBuilder res = new StringBuilder(); for (String s : tem) { res.append("/" + s); } if (res.length() == 0) { return "/"; } else { return res.toString(); } } }
public class Solution { public String simplifyPath(String path) { if (path == null || path.length() == 0) { return ""; } Stack<String> stack = new Stack<String>(); String[] list = path.split("/"); for (String s : list) { if (s.equals( ".") || s.length() == 0) { continue; } else if (s.equals("..")) { if (! stack.isEmpty()) { stack.pop(); } } else { stack.push(s); } } StringBuilder res = new StringBuilder(); while (!stack.isEmpty()) { String tem = stack.pop(); res.insert(0, "/" + tem ); } if (res.length() == 0) { return "/"; } else { return res.toString(); } } }
没有评论:
发表评论