[登录 · 注册]
• 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         }//while
17         ptrOfPath ++;
18         if(!element.equals(".") && !element.equals("..") && !element.equals("/"))
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(".")){
38                 }
39                 ptrOfPath++;
40                 continue;
41             }//if
42             else{
43                 element += path.charAt(ptrOfPath ++);
44             }
45         }//while
46         if(stack.size() == 0)
47             return "/";
48         //遍历list获取结果
49         for(String str : stack){
50             result += "/";
51             result += str;
52         }//for
53
54         return result;
55     }
56 }```
• 【推广】 阿里云小站-上云优惠聚集地（新老客户同享）更有每天限时秒杀！
【推广】 云服务器低至0.95折 1核2G ECS云服务器8.1元/月
【推广】 阿里云老用户升级四重礼遇享6.5折限时折扣！
• 原文：https://www.cnblogs.com/luckygxf/p/4218972.html