首页 > 代码库 > Simplify Path

Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

思路

以/为分界符split,如/a/./b/../../c/,分成a,.,b,..,..,c这样,将a,b..依次入栈,如果,是..出栈,最后从栈底遍历到栈底为最后的路径。因为最后要从栈底遍历到栈顶,我用的是list不是stack

 1 import java.util.ArrayList; 2 import java.util.List; 3  4 public class Solution { 5     public String simplifyPath(String path) { 6         List<String> stack = new ArrayList<String>();            //这里的List有stack的作用 7         String result = ""; 8          9         int ptrOfPath = 1;10         String element = "";11         while(ptrOfPath < path.length() && path.charAt(ptrOfPath) == ‘/‘)12             ptrOfPath++;13         while(ptrOfPath < path.length() && path.charAt(ptrOfPath) != ‘/‘){14             element += path.charAt(ptrOfPath);15             ptrOfPath++;16         }//while17         ptrOfPath ++;18         if(!element.equals(".") && !element.equals("..") && !element.equals("/"))19             stack.add(element);20         element = "";21         boolean startNewWord = false;22         while(ptrOfPath < path.length()){23             if(startNewWord == true)24             {25                 element = "";26                 startNewWord = false;27             }28             if(path.charAt(ptrOfPath) == ‘/‘ || ptrOfPath == path.length() - 1){29                 startNewWord = true;30                 if(ptrOfPath == path.length() - 1 && path.charAt(ptrOfPath) != ‘/‘)31                     element += path.charAt(ptrOfPath);32                 if(element.length() != 0 && element.equals("..")){33                     if(stack.size() != 0)34                         stack.remove(stack.size() - 1);                //出栈35                 }36                 else if(element.length() != 0 && !element.equals(".")){37                     stack.add(element);                                //入栈38                 }39                 ptrOfPath++;40                 continue;41             }//if42             else{43                 element += path.charAt(ptrOfPath ++);44             }45         }//while46         if(stack.size() == 0)47             return "/";48         //遍历list获取结果49         for(String str : stack){50             result += "/";51             result += str;52         }//for53         54         return result;55     }56 }

 

Simplify Path