码迷,mamicode.com
首页 > 其他好文 > 详细

71. Simplify Path

时间:2016-03-11 06:27:04      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

主要是用一个stack记录,如果碰到的是“..”,那么如果堆栈不为空,弹出堆栈里面的前一个

如果是“.”,那么什么都不做

 1     public String simplifyPath1(String path) {
 2         if(path == null || path.length() == 0) {
 3             return "";
 4         }
 5         StringBuilder sb = new StringBuilder();
 6         Stack<String> stack = new Stack<String>();
 7         int i = 0;
 8         while(i < path.length()) {
 9             StringBuilder temp = new StringBuilder();
10             int index = i;
11             while(i < path.length() && path.charAt(i) != ‘/‘) {
12                 temp.append(path.charAt(i));
13                 i++;
14             }
15             if(index != i) {
16                 String str = temp.toString();
17                 if(str.equals("..")) {
18                     if(!stack.isEmpty()) {
19                         stack.pop();
20                     }
21                 } else if(!str.equals(".")) {
22                     stack.push(str);
23                 }
24             }
25             i++;
26         }
27         int size = stack.size();
28         for(int j = 0; j < size; j++) {
29             sb.insert(0,stack.pop());
30             sb.insert(0,"/");
31         }
32         return (sb.length() == 0)? "/":sb.toString();
33     }

bug记录

第30,31行是insert,不是append,因为stack是倒序的

 

71. Simplify Path

标签:

原文地址:http://www.cnblogs.com/warmland/p/5264175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!