Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Solution:
1 public class Solution { 2 public String simplifyPath(String path) { 3 if (path.isEmpty()) return ""; 4 5 StringBuilder builder = new StringBuilder(); 6 builder.append('/'); 7 int index = 1; 8 while (index<path.length()){ 9 //get the next directory command. 10 int next = index; 11 while (next<path.length() && path.charAt(next)!='/') next++; 12 String dir = path.substring(index,next); 13 if (dir.equals(".") || dir.isEmpty()){ 14 index = next+1; 15 continue; 16 } else if (dir.equals("..")){ 17 pathBack(builder); 18 } else { 19 builder.append(dir); 20 builder.append('/'); 21 } 22 index = next+1; 23 } 24 25 if (builder.length()>1 && builder.charAt(builder.length()-1)=='/') 26 builder.deleteCharAt(builder.length()-1); 27 return builder.toString(); 28 } 29 30 public void pathBack(StringBuilder builder){ 31 builder.deleteCharAt(builder.length()-1); 32 while (builder.length()>0 && builder.charAt(builder.length()-1)!='/') 33 builder.deleteCharAt(builder.length()-1); 34 if (builder.length()==0) builder.append('/'); 35 } 36 }