首页 > 其他 > 详细

Simplify Path

时间:2015-06-29 02:05:07      阅读:195      评论:0      收藏:0      [点我收藏+]

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

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

?

public class Solution {
    public String simplifyPath(String path) {
        if (path==null || path.length()==0) {
        	return new String();
        }
        String[] arr = path.split("/");
        Stack<String> stack = new Stack<String>();
        for (int i=0; i<arr.length; i++) {
        	if (arr[i].equals("..")) {
        		if (stack.size() > 0) {
        			stack.pop();
        		} else {
        			continue;
        		}
        	} else if (arr[i].equals(".") || arr[i].length()==0) {
        		continue;
        	} else {
        		stack.push(arr[i]);
        	}
        }
        StringBuilder res = new StringBuilder();
        if (stack.size()==0) {
            return "/";
        }
        Stack<String> stack2 = new Stack<String>();
        while (stack.size() > 0) {
        	stack2.push(stack.pop());
        }
        while (stack2.size() > 0) {
        	res.append("/");
        	res.append(stack2.pop());
        }
        return res.toString();
    }
}

?

Simplify Path

原文:http://hcx2013.iteye.com/blog/2222703

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