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

LeetCode-Simplify Path

时间:2015-01-04 06:27:08      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

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

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

click to show corner cases.

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 }

 

LeetCode-Simplify Path

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4200266.html

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