71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
Example
"/home/"
, => "/home"
"/a/./b/../../c/"
, => "/c"
Challenge
-
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 class Solution { 2 /* 归下类的话,有四种字符串: 3 1. "/":为目录分隔符,用来分隔两个目录。 4 2. ".":当前目录 5 3. "..":上层目录 6 4. 其他字符串:目录名 7 8 简化的核心是要找出所有的目录,并且如果遇到"..",需要删除上一个目录。 9 */ 10 public String simplifyPath(String path) { 11 if (path == null || path.length() == 0) return path; 12 13 String[] subPath = path.split("/"); 14 Stack<String> stack = new Stack<>(); 15 for (int i = 0; i < subPath.length; i++) { 16 String str = subPath[i]; 17 if (!(str.equals(".") || str.isEmpty())) { // for . and empty string, we do nothing. 18 if (str.equals("..")) { // we need to remove one upper directory 19 if (!stack.isEmpty()) { 20 stack.pop(); 21 } 22 } else { 23 stack.push("/" + str); 24 } 25 } 26 } 27 28 StringBuilder sb = new StringBuilder(); 29 for (String str : stack) { 30 sb.append(str); 31 } 32 return sb.length() == 0 ? "/" : sb.toString(); 33 } 34 35 }
Use StringBuilder
1 public class Solution { 2 public static String simplifyPath(String path) { 3 if (path == null || path.length() == 0) return path; 4 5 String[] subPath = path.split("/"); 6 StringBuilder sb = new StringBuilder(""); 7 for (int i = 0; i < subPath.length; i++) { 8 String str = subPath[i]; 9 if (!(str.equals(".") || str.isEmpty())) { // for . and empty string, we do nothing. 10 if (str.equals("..")) { // we need to remove one upper directory 11 if (sb.length() > 1) { 12 int k = sb.length() - 1; 13 while (sb.length() >= 1 && sb.charAt(k) != '/') { 14 sb.deleteCharAt(k); 15 k--; 16 } 17 sb.deleteCharAt(k); // "delete the last /" 18 } 19 } else { 20 sb.append("/"); 21 sb.append(str); 22 } 23 } 24 } 25 if (sb.length() == 0) { 26 return "/"; 27 } 28 return sb.toString(); 29 } 30 }