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

Simplify Path

时间:2014-09-19 12:13:05      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   io   java   ar   strong   for   div   

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

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

Corner Cases:

  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes ‘/‘ together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".

答案

public class Solution {
    public String simplifyPath(String path) {
        if(path==null||path.length()==0)
        {
            return path;
        }
        LinkedList<String> list=new LinkedList<String>();
        int first,second;
        String p;
        for(first=1,second=0;first<path.length();first=second+1)
        {
            second=path.indexOf('/',first);
            if(second==first){
                continue;
            }
            if(second<0)
            {
                p=path.substring(first);
                second=path.length();
            }
            else 
            {
                p=path.substring(first,second);
            }
            if(p.equals("."))
            {
                continue;
            }
            if(p.equals(".."))
            {
                if(list.size()>0)
                {
                    list.remove(list.size()-1);
                }
                continue;
            }
            list.add(p);
        }
        String dest="";
        for(String element:list){
            dest+="/"+element;
        }
        if(dest==""){
            dest="/";
        }
        return dest;
    }
}


Simplify Path

标签:des   style   color   io   java   ar   strong   for   div   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39393735

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