首页 > 其他 > 详细

Simplify Path

时间:2014-11-25 00:23:33      阅读:269      评论:0      收藏:0      [点我收藏+]

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

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

算法:根据/把path分割,再逐个判断

public class Solution {
    public String simplifyPath(String path) {
        String[] strs = path.split("/");
        Stack<String> s = new Stack<String>();
        for(int i=0;i<strs.length;i++){
            if(strs[i].equals(".")){
            }else if(strs[i].equals("..")){
                if(!s.isEmpty())
                    s.pop();
            }else if(strs[i].length()>0){
                s.push(strs[i]);
            }
        }
        StringBuilder sb = new StringBuilder();
        Iterator<String> it = s.iterator();
        while(it.hasNext()){
            String t = it.next();
            sb.append("/").append(t);
        }
        String r=sb.toString();
        if(r.length()==0)
            r+="/";
        return r;
    }
}





Simplify Path

原文:http://blog.csdn.net/u010786672/article/details/41456083

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!